package logic

import (
	"encoding/csv"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"github.com/go-resty/resty/v2"
	"github.com/gogap/logs"
	"github.com/shopspring/decimal"
	"github.com/spf13/viper"
	"io/ioutil"
	"log"
	"os"
	"strconv"
	"strings"
	"time"
	"yundian/internel/app/dao"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/resphelper/placeresp"
	"yundian/internel/app/models/agentincome"
	"yundian/internel/app/models/cashlog"
	"yundian/internel/app/models/devices"
	"yundian/internel/app/models/dividendslog"
	"yundian/internel/app/models/membermodel"
	"yundian/internel/app/models/orders"
	"yundian/internel/app/models/placemodel"
	"yundian/internel/app/models/prices"
	"yundian/internel/app/models/users"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	"yundian/internel/pkg/utils"
	"yundian/internel/pkg/wechatpay"
)

type SyncLogic struct {
}

func NewSyncLogic() *SyncLogic {
	return &SyncLogic{}
}

// -----------------------更新用户相关----------------------------------//
func (logic *SyncLogic) SyncOpenid() {
	path := fmt.Sprintf("./data/users/%s/%s", "openid", "20210329001415")
	//

	for i := 2465; i <= 2464; i++ {
		b, _ := ioutil.ReadFile(path + fmt.Sprintf("/%d.html", i))

		doc, err := goquery.NewDocumentFromReader(strings.NewReader(string(b)))
		if err != nil {
			log.Fatal(err)
		}

		var phone string
		doc.Find(".layui-col-xs6").Find("label").Each(func(i int, selection *goquery.Selection) {
			if i == 1 {
				phone = selection.Text()
			}
		})

		var openid string
		doc.Find(".layui-card:nth-child(2)").Each(func(i int, selection *goquery.Selection) {
			selection.Find(".layui-col-sm6").Each(func(j int, sel *goquery.Selection) {
				if sel.Find(".layui-form-label").Text() == "收款账号openId:" {
					openid = sel.Find(".layui-form-mid").Text()
				}
			})
		})

		if openid != "无" && openid != "" && phone != "无此代理信息" {
			// 通过手机号码查询用户
			m := users.New()
			global.Orm.Table("users").Where("phone = ?", phone).Find(&m)
			if m.ID > 0 {
				global.Orm.Table("users").Model(&m).Update("openid", openid)
			}
		}

	}

}
func (logic *SyncLogic) UpdateUsersOpenId(cookie string) ([]string, error) {
	path := fmt.Sprintf("./data/users/%s/%s", "openid", time.Now().Format("20060102150405"))

	var strs []string

	for i := 2465; i <= 2698; i++ {
		url := fmt.Sprintf("http://mng.yundian.ink/mng/10041/business/cashWithdrawal/agent/info.html?id=%d", i)
		err := logic.DoRequestUsersOpenid(i, url, path, cookie) // 抓取订单信息
		if err != nil {
			return nil, err
		}
	}

	return strs, nil
}
func (logic *SyncLogic) DoRequestUsersOpenid(userId int, url, path, cookie string) error {
	client := resty.New()
	resp, err := client.R().
		SetHeader("Cookie", cookie).
		Get(url)
	if err != nil {
		return err
	}
	msg := new(msgResp)
	_ = json.Unmarshal(resp.Body(), &msg)
	if msg.Code != 200 && msg.Msg != "" {
		return errors.New(msg.Msg)
	}
	// 创建
	err = helper.MakeDir(path)
	if err != nil {
		return err
	}
	err = ioutil.WriteFile(path+fmt.Sprintf("/%d.html", userId), resp.Body(), 666)
	if err != nil {
		return err
	}
	return nil
}
func (logic *SyncLogic) SyncUserPloys(cookie string) {
	path := fmt.Sprintf("./data/users/ploys/%s", time.Now().Format("20060102150405"))
	// http://mng.yundian.ink/takeOrder/10041/takeOder/tactics/list.data
	client := resty.New()
	for i := 1; i <= 1; i++ {
		m := map[string]string{}
		m["page"] = strconv.Itoa(i)
		m["limit"] = strconv.Itoa(10)
		resp, err := client.R().
			SetHeader("Content-Type", "application/x-www-form-urlencoded").
			SetFormData(m).
			SetHeader("Cookie", cookie).
			//SetResult(placeType).    // or SetResult(AuthSuccess{}).
			Post("http://mng.yundian.ink/takeOrder/10041/takeOder/tactics/list.data")
		if err != nil {
			log.Println(err)
		}
		msg := new(msgResp)
		_ = json.Unmarshal(resp.Body(), &msg)
		if msg.Msg != "" {
			log.Println(msg.Msg)
		}
		// 创建
		err = helper.MakeDir(path)
		if err != nil {
			log.Println(err)
		}

		err = ioutil.WriteFile(path+fmt.Sprintf("/%d.json", i), resp.Body(), 666)
		if err != nil {
			log.Println(err)
		}
	}
}

// 更新用户信息逻辑
func (logic *SyncLogic) UpdateUsersLogic(page, pageSize int, cookie string) ([]string, error) {
	path := fmt.Sprintf("./data/users/%s", time.Now().Format("20060102150405"))
	//path := fmt.Sprintf("./data/users/%s", "20210328140642")

	//url := "http://mng.cnman.cn/mng/10082/place/list.data"
	//err := logic.doRequestPlaces(page, pageSize, url, path, cookie) // 抓取网点信息
	//if err != nil {
	//	return nil, err
	//}

	//urlUser := "http://mng.cnman.cn/mng/10082/user/agent/list.data"
	urlUser := "http://mng.cnman.cn/mng/10082/user/agent/list.data"
	logic.doRequestUsers(page, pageSize, urlUser, path, cookie) // 抓取代理商信息
	//if err != nil {
	//	return nil, err
	//}

	var strs []string

	for i := 1; i <= page; i++ {
		// 生成代理商信息、商户信息
		strUser := logic.DotaskUsers(i, path)
		strs = append(strs, strUser)
		// 生成商户信息
		strPlace := logic.doTaskPlaces(i, path)

		strs = append(strs, strPlace)
	}

	return strs, nil
}

// 更新用户信息逻辑
func (logic *SyncLogic) UpdateYCUsersLogic(page, pageSize int, cookie string) ([]string, error) {
	path := fmt.Sprintf("./data/users/%s", time.Now().Format("20060102150405"))
	//path := fmt.Sprintf("./data/users/%s", "20210328140642")

	//url := "http://mng.cnman.cn/mng/10082/place/list.data"
	//err := logic.doRequestPlaces(page, pageSize, url, path, cookie) // 抓取网点信息
	//if err != nil {
	//	return nil, err
	//}

	//urlUser := "http://mng.cnman.cn/mng/10082/user/agent/list.data"
	urlUser := "http://mng.kdcgx.com/mng/10032/user/agent/list.data"
	logic.doRequestUsers(page, pageSize, urlUser, path, cookie) // 抓取代理商信息
	//if err != nil {
	//	return nil, err
	//}

	var strs []string

	//for i := 1; i <= page; i++ {
	//	// 生成代理商信息、商户信息
	//	strUser := logic.dotaskUsers(i, path)
	//	strs = append(strs, strUser)
	//	// 生成商户信息
	//	strPlace := logic.doTaskPlaces(i, path)
	//
	//	strs = append(strs, strPlace)
	//}

	return strs, nil
}

//func (logic *SyncLogic) UpdateTable()  {
//	usersql := `
//CREATE TABLE users  (
//  id int(11) NOT NULL AUTO_INCREMENT,
//  parent_id int(11) NULL DEFAULT NULL COMMENT '父节点ID',
//  role_id int(11) NULL DEFAULT NULL COMMENT '角色ID',
//  is_admin tinyint(1) NULL DEFAULT NULL COMMENT '用户类型 1管理员 2运营商 3代理商 4员工',
//  openid varchar(0) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '以后如果有 微信开放平台  可以使用',
//  password varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '密码-后台登录的密码',
//  name char(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '姓名',
//  user_name char(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '用户名',
//  nick_name char(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '昵称',
//  sex tinyint(1) NULL DEFAULT NULL COMMENT '性别',
//  phone char(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '手机号码-用于登录',
//  phone_code char(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
//  avatar varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '头像',
//  country char(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '国家',
//  province char(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '省份',
//  city char(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '城市',
//  address varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '详细地址',
//  profit_type tinyint(2) NULL DEFAULT NULL COMMENT '分润模式',
//  profit_is_visible tinyint(1) NULL DEFAULT NULL,
//  profit_proportion tinyint(4) NULL DEFAULT NULL COMMENT '分成比例',
//  status tinyint(2) NULL DEFAULT 1,
//  is_delete tinyint(1) NULL DEFAULT 0,
//  is_place tinyint(1) NULL DEFAULT 0,
//  wx_income_qrcode varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '收款二维码地址-暂时用不上',
//  last_login_ip char(15) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '最后登录IP',
//  last_login_time int(11) NULL DEFAULT NULL COMMENT '最后登录时间',
//  create_at int(11) NULL DEFAULT NULL,
//  update_at int(11) NULL DEFAULT NULL,
//  delete_at int(11) NULL DEFAULT NULL,
//  agent_child_count int(11) NULL DEFAULT NULL,
//  place_count int(11) NULL DEFAULT NULL,
//  device_count int(11) NULL DEFAULT NULL,
//  agent_count int(11) NULL DEFAULT NULL,
//  login_count int(11) NULL DEFAULT NULL,
//  PRIMARY KEY (id) USING BTREE
//) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '后台用户表-管理员、运营商、员工' ROW_FORMAT = Dynamic;`
//
//	placeSql := `
//CREATE TABLE places  (
//  id int(11) NOT NULL AUTO_INCREMENT,
//  place_name varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '商户名称',
//  class_name varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '商户类型名称',
//  user_id int(11) NOT NULL COMMENT '商户所属代理商ID',
//  user_name varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '用户名',
//  place_img varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '网点图片',
//  longitude char(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '经度',
//  latitude char(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '纬度',
//  place_desc varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '网点描述',
//  status tinyint(2) NULL DEFAULT NULL COMMENT '状态 1启用 2禁用 3问题商户',
//  address varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '地址',
//  device_count int(11) NULL DEFAULT NULL COMMENT '设备条数',
//  login_count int(11) NULL DEFAULT 0 COMMENT '登录次数',
//  area_code varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '区域code',
//  country char(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
//  province char(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '省份',
//  city char(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '城市',
//  city_area char(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '区、县',
//  opening_time char(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '营业时间',
//  closeing_time char(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '营业时间',
//  business_hours char(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
//  wx_openid varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '微信公众号openid',
//  last_login_ip char(15) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '最后登录IP',
//  last_login_time int(11) NULL DEFAULT NULL COMMENT '最后登录时间',
//  create_at int(11) NULL DEFAULT NULL COMMENT '创建时间',
//  update_at int(11) NULL DEFAULT NULL COMMENT '修改时间',
//  level char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'E' COMMENT '商户等级',
//  used_rate float(10, 2) NULL DEFAULT 0.00,
//  PRIMARY KEY (id) USING BTREE
//) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '商户表' ROW_FORMAT = Dynamic;
//
//`
//	global.Orm.Exec(`DROP TABLE IF EXISTS places;`)
//	global.Orm.Exec(`DROP TABLE IF EXISTS users;`)
//	global.Orm.Exec(usersql)
//	global.Orm.Exec(placeSql)
//	global.Orm.Exec(`INSERT INTO users VALUES (1, 0, 1, 1, '', '3d9c616a1eecba0130f75a35f036de22845df9a27f5a8b4d7074aa0be8d4f747', '昀电', '昀电', '昀电', 1, '176', '+86', '', '', '', '', '', 1, NULL, 0, 1, 0, 0, '', '', 0, 1594364822, 1609210322, 0, 0, 0, 0, 0, 0);`)
//	global.Orm.Exec(`INSERT INTO users VALUES (2, 0, 2, 2, '', '3d9c616a1eecba0130f75a35f036de22845df9a27f5a8b4d7074aa0be8d4f747', '余鑫', '余鑫', '余鑫', 1, '188', '+86', '', '', '', '', '', 1, NULL, 0, 1, 0, 0, '', '', 0, 1594364822, 1609210322, 0, 0, 0, 0, 0, 0);`)
//}

// 抓取网点信息
func (logic *SyncLogic) doRequestPlaces(page, pageSize int, url, path, cookie string) error {
	client := resty.New()
	for i := 1; i <= page; i++ {
		m := map[string]string{}
		m["page"] = strconv.Itoa(i)
		m["limit"] = strconv.Itoa(pageSize)
		resp, err := client.R().
			SetHeader("Content-Type", "application/x-www-form-urlencoded").
			SetFormData(m).
			SetHeader("Cookie", cookie).
			//SetResult(placeType).    // or SetResult(AuthSuccess{}).
			Post(url)
		if err != nil {
			return err
		}
		msg := new(msgResp)
		_ = json.Unmarshal(resp.Body(), &msg)
		if msg.Msg != "" {
			return errors.New(msg.Msg)
		}
		// 创建
		err = helper.MakeDir(path)
		if err != nil {
			return err
		}

		err = ioutil.WriteFile(path+fmt.Sprintf("/places-%d.json", i), resp.Body(), 666)
		if err != nil {
			return err
		}
	}
	return nil
}

// 抓取代理商信息
func (logic *SyncLogic) doRequestUsers(page, pageSize int, url, path, cookie string) error {
	client := resty.New()
	for i := 1; i <= page; i++ {
		m := map[string]string{}
		m["page"] = strconv.Itoa(i)
		m["limit"] = strconv.Itoa(pageSize)
		resp, err := client.R().
			SetHeader("Content-Type", "application/x-www-form-urlencoded").
			SetFormData(m).
			SetHeader("Cookie", cookie).
			//SetResult(placeType).    // or SetResult(AuthSuccess{}).
			Post(url)
		if err != nil {
			return err
		}
		msg := new(msgResp)
		_ = json.Unmarshal(resp.Body(), &msg)
		if msg.Msg != "" {
			return errors.New(msg.Msg)
		}
		// 创建
		err = helper.MakeDir(path)
		if err != nil {
			return err
		}

		err = ioutil.WriteFile(path+fmt.Sprintf("/users-%d.json", i), resp.Body(), 666)
		if err != nil {
			return err
		}
	}
	return nil
}

func (logic *SyncLogic) DotaskUsers(page int, path string) string {
	for i := 1; i <= page; i++ {
		lists := new(usersModelGenerated)
		viper.SetConfigFile(path + fmt.Sprintf("/users-%d.json", i))
		if err := viper.ReadInConfig(); err != nil {
			log.Fatal("viper.ReadInConfig failed : ", err.Error())
		}

		// 反序列化到struct
		if err := viper.Unmarshal(lists); err != nil {
			log.Fatal("viper.Unmarshal failed : ", err.Error())
		}

		// 写入数据库
		ucount := 0
		ccount := 0
		for _, lst := range lists.Body.Data {
			m := &users.UserModel{}
			//
			//if lst.ID == 100000 {
			//	log.Println("运营商")
			//	continue
			//}

			// 100000 运营商  100067 100950 100952 101098 101071  代理商
			//if lst.ID == 100067 || lst.ID == 100950 || lst.ID == 100952 || lst.ID == 101098 || lst.ID == 101071 {
			//	m.RoleID = 3
			//	m.IsAdmin = 3
			//	m.IsPlace = 0
			//} else if lst.ID == 100001 || lst.ID == 100060 || lst.ID == 100325 || lst.ID == 100523 || lst.ID == 100555 ||
			//	lst.ID == 100593 || lst.ID == 100639 || lst.ID == 100686 || lst.ID == 100694 || lst.ID == 100829 ||
			//	lst.ID == 100852 || lst.ID == 100889 || lst.ID == 100981 || lst.ID == 101058 || lst.ID == 101069 { // 老板，有多个商户
			//	m.RoleID = 3
			//	m.IsAdmin = 3
			//	m.IsPlace = 2
			//} else { // 商户
			//	m.RoleID = 3
			//	m.IsAdmin = 3
			//	m.IsPlace = 1
			//}

			//if lst.ParentID == 100000 {
			//	m.ParentID = 2
			//} else {
			//	m.ParentID = lst.ParentID
			//}

			m.ID = lst.ID + 300000
			m.ParentID = lst.ParentID + 300000
			m.IsAdmin = 3
			if lst.LevelTypeName == "代理商" {
				m.RoleID = 20
			} else if lst.LevelTypeName == "商户" {
				m.RoleID = 7
				m.IsPlace = 1
			} else if lst.LevelTypeName == "业务员" {
				m.RoleID = 6
				m.IsPlace = 1
			} else if lst.LevelTypeName == "二级同盟" {
				m.RoleID = 5
				m.IsPlace = 1
			} else if lst.LevelTypeName == "分公司" {
				m.RoleID = 11
				m.IsPlace = 3
			} else {
				m.IsPlace = 0
				m.RoleID = 0
			}

			m.Status = uint8(lst.Status)

			m.Openid = ""
			m.Password = utils.EncryptPassword(lst.Phone)

			m.Name = lst.Name
			m.UserName = lst.UserName
			m.NickName = lst.Nickname
			if lst.Sex == 0 {
				m.Sex = 2 // 1男 2 女
			} else {
				m.Sex = 1
			}
			m.Phone = lst.Phone
			m.PhoneCode = lst.PhoneCode
			m.Avatar = lst.FaceImg
			m.Country = lst.Country
			m.Province = lst.Province
			m.City = lst.City
			m.Address = lst.Address

			m.ProfitType = lst.ProfitType
			m.ProfitProportion = int(lst.ProfitProportion)

			m.IsDelete = 0

			m.WxIncomeQrcode = lst.WxIncomeQrcode
			m.LastLoginIp = ""
			m.LastLoginTime = 0

			m.CreateAt = dingo.Time(wechatpay.StrTimeToInt(lst.CreateDate))
			m.UpdateAt = 0
			m.DeleteAt = 0

			m.AgentCount = lst.AgentCount
			m.AgentChildCount = lst.AgentChildCount
			m.PlaceCount = lst.PlaceCount
			m.DeviceCount = lst.DeviceCount

			t := time.Unix(wechatpay.StrTimeToInt(lst.CreateDate), 0)
			if m.IsPlace == 0 {
				m.UserNo = utils.Join("DL", t.Format("20060102150405"))
			} else {
				m.UserNo = utils.Join("SH", t.Format("20060102150405"))
			}
			m.IsBind = 0

			var count int64
			global.Orm.Table("users").Where("id = ?", m.ID).Count(&count)
			if count > 0 {
				ucount++
				global.Orm.Table("users").Where("id = ?", m.ID).Model(&m).Updates(m)
			} else { // 新增
				ccount++
				global.Orm.Table("users").Create(m)
			}
		}
		//fmt.Printf("当前页面%d, 更新成功%d条，新增成功%d条 \n", i, ucount, ccount)
		str := fmt.Sprintf("当前页面%d, 更新成功%d条，新增成功%d条 \n", i, ucount, ccount)
		return str
	}
	str := fmt.Sprintf("更新成功%d条，新增成功%d条 \n", 0, 0)
	return str
}

func (logic *SyncLogic) DotaskSCUsers(page int, path string) {
	for i := 1; i <= page; i++ {

		lists := new(usersModelGenerated)
		viper.SetConfigFile(path + fmt.Sprintf("/users-%d.json", i))
		if err := viper.ReadInConfig(); err != nil {
			log.Fatal("viper.ReadInConfig failed : ", err.Error())
		}

		// 反序列化到struct
		if err := viper.Unmarshal(lists); err != nil {
			log.Fatal("viper.Unmarshal failed : ", err.Error())
		}

		f, err := os.Create("./data/users/scusers.xls")
		if err != nil {
			panic(err)
		}
		defer f.Close()

		f.WriteString("\xEF\xBB\xBF") // 写入UTF-8 BOM

		w := csv.NewWriter(f)
		w.Write([]string{"用户ID", "名称", "姓名", "手机号码", "分成比例", "用户等级", "上级用户ID", "创建时间", "是否KA", "奖励权益", "提现权益"})

		//w.Write([]string{"1","张三","23"})
		for _, lst := range lists.Body.Data {
			w.Write([]string{
				strconv.Itoa(lst.ID),
				lst.UserName,
				lst.Name,
				lst.Phone,
				decimal.NewFromFloat(lst.ProfitProportion).String(),
				lst.LevelTypeName,
				strconv.Itoa(lst.ParentID),
				lst.CreateDate,
				"2",
				"2",
				"2",
			})
		}
		w.Flush()
	}
}

func (logic *SyncLogic) doTaskPlaces(page int, path string) string {
	for i := 1; i <= page; i++ {
		lists := new(placesGenerated)
		viper.SetConfigFile(path + fmt.Sprintf("/places-%d.json", i))
		if err := viper.ReadInConfig(); err != nil {
			log.Fatal("viper.ReadInConfig failed : ", err.Error())
		}

		// 反序列化到struct
		if err := viper.Unmarshal(lists); err != nil {
			log.Fatal("viper.Unmarshal failed : ", err.Error())
		}

		ccount := 0
		ucount := 0
		// 写入数据库
		for _, lst := range lists.Body.Data {
			p := &placemodel.PlaceModel{}
			p.Id = lst.ID
			p.ClassName = lst.TypeName
			p.PlaceName = lst.Name
			p.PlaceImg = lst.ImgPath
			p.UserID = lst.UserID
			p.UserName = lst.UserName

			p.DeviceCount = lst.DeviceCount
			//p.WxOpenid = ""

			p.Address = lst.Address
			p.RegionCode = lst.AreaCode
			p.Status = int8(lst.State)
			p.CreateAt = dingo.Time(wechatpay.StrTimeToInt(lst.CreateDate))
			p.UpdateAt = dingo.Time(wechatpay.StrTimeToInt(lst.UpdateDate))
			p.IsTianHai = 1

			var count int64
			global.Orm.Table("places").Where("id = ?", lst.ID).Count(&count)
			if count > 0 {
				ucount++
				global.Orm.Table("places").Where("id = ?", lst.ID).Model(&p).Updates(p)
			} else { // 新增
				ccount++
				global.Orm.Table("places").Create(p)
			}
		}
		str := fmt.Sprintf("当前页面%d, 更新成功%d条，新增成功%d条 \n", i, ucount, ccount)
		return str
	}
	str := fmt.Sprintf("更新成功%d条，新增成功%d条 \n", 0, 0)
	return str
}

type usersModelGenerated struct {
	Code int `json:"code"`
	Body struct {
		Total int `json:"total"`
		Data  []struct {
			ID               int     `json:"id"`
			RoleType         int     `json:"roleType"`
			LevelType        int     `json:"levelType"`
			Status           int     `json:"status"`
			ProfitType       int     `json:"profitType"`
			ProfitProportion float64 `json:"profitProportion"`
			AgentChildCount  int     `json:"agentChildCount"`
			PlaceCount       int     `json:"placeCount"`
			DeviceCount      int     `json:"deviceCount"`
			SettingInfo      string  `json:"settingInfo"`
			FunctionSetting  string  `json:"functionSetting"`
			ParentID         int     `json:"parentId"`
			RootID           int     `json:"rootId"`
			LeftNum          int     `json:"leftNum"`
			RightNum         int     `json:"rightNum"`
			UpdateDate       string  `json:"updateDate"`
			CreateDate       string  `json:"createDate"`
			LevelTypeName    string  `json:"levelTypeName"`
			Phone            string  `json:"phone"`
			PhoneCode        string  `json:"phoneCode"`
			Sex              int     `json:"sex"`
			Nickname         string  `json:"nickname"`
			Name             string  `json:"name"`
			UserName         string  `json:"userName"`
			UserID           int     `json:"userId"`
			IsMain           bool    `json:"isMain"`
			RoleTypeName     string  `json:"roleTypeName"`
			SexName          string  `json:"sexName"`
			AgentCount       int     `json:"agentCount"`
			HaveChild        bool    `json:"haveChild"`
			PhoneNumber      string  `json:"phoneNumber"`
			IsLeaf           bool    `json:"isLeaf"`
			IsRoot           bool    `json:"isRoot"`
			WxIncomeQrcode   string  `json:"wxIncomeQrcode,omitempty"`
			FaceImg          string  `json:"faceImg,omitempty"`
			Country          string  `json:"country,omitempty"`
			Province         string  `json:"province,omitempty"`
			City             string  `json:"city,omitempty"`
			Address          string  `json:"address,omitempty"`
		} `json:"data"`
	} `json:"body"`
}

//type placesGenerated struct {
//	Body struct {
//		Total int `json:"total"`
//		Data  []struct {
//			ID           int    `json:"id"`
//			Name         string `json:"name"`
//			TypeClassify int    `json:"typeClassify"`
//			TypeID       int    `json:"typeId"`
//			UserID       int    `json:"userId"`
//			DeviceCount  int    `json:"deviceCount"`
//			ProfitMode   int    `json:"profitMode"`
//			ImgPaths     string `json:"imgPaths"`
//			State        int    `json:"state"`
//			AreaCode     string `json:"areaCode"`
//			ConfigFlag   string `json:"configFlag"`
//			UpdateDate   string `json:"updateDate"`
//			CreateDate   string `json:"createDate"`
//			Agent        struct {
//				ID               int    `json:"id"`
//				RoleType         int    `json:"roleType"`
//				LevelType        int    `json:"levelType"`
//				Status           int    `json:"status"`
//				ProfitType       int    `json:"profitType"`
//				ProfitProportion int    `json:"profitProportion"`
//				AgentChildCount  int    `json:"agentChildCount"`
//				PlaceCount       int    `json:"placeCount"`
//				DeviceCount      int    `json:"deviceCount"`
//				SettingInfo      string `json:"settingInfo"`
//				FunctionSetting  string `json:"functionSetting"`
//				ParentID         int    `json:"parentId"`
//				RootID           int    `json:"rootId"`
//				LeftNum          int    `json:"leftNum"`
//				RightNum         int    `json:"rightNum"`
//				UpdateDate       string `json:"updateDate"`
//				CreateDate       string `json:"createDate"`
//				UserID           int    `json:"userId"`
//				IsMain           bool   `json:"isMain"`
//				RoleTypeName     string `json:"roleTypeName"`
//				AgentCount       int    `json:"agentCount"`
//				HaveChild        bool   `json:"haveChild"`
//				IsLeaf           bool   `json:"isLeaf"`
//				IsRoot           bool   `json:"isRoot"`
//			} `json:"agent"`
//			Cpi              int      `json:"cpi"`
//			TypeName         string   `json:"typeName"`
//			UserName         string   `json:"userName"`
//			StateName        string   `json:"stateName"`
//			ImgPathArray     []string `json:"imgPathArray"`
//			ProfitModeName   string   `json:"profitModeName"`
//			Cpistr           string   `json:"cpistr"`
//			TypeClassifyName string   `json:"typeClassifyName"`
//			ImgPath          string   `json:"imgPath"`
//			Province         string   `json:"province,omitempty"`
//			City             string   `json:"city,omitempty"`
//			CityArea         string   `json:"cityArea,omitempty"`
//			Address          string   `json:"address,omitempty"`
//			OpeningTime      string   `json:"openingTime,omitempty"`
//			CloseingTime     string   `json:"closeingTime,omitempty"`
//			BusinessHours    string   `json:"businessHours,omitempty"`
//		} `json:"data"`
//	} `json:"body"`
//}

type placesGenerated struct {
	Code int `json:"code"`
	Body struct {
		Total int `json:"total"`
		Data  []struct {
			ID             int    `json:"id"`
			Name           string `json:"name"`
			TypeClassify   int    `json:"typeClassify"`
			TypeID         int    `json:"typeId"`
			UserID         int    `json:"userId"`
			DeviceCount    int    `json:"deviceCount"`
			ProfitMode     int    `json:"profitMode"`
			ImgPaths       string `json:"imgPaths"`
			State          int    `json:"state"`
			Authentication int    `json:"authentication"`
			AreaCode       string `json:"areaCode"`
			DetailInfo     string `json:"detailInfo,omitempty"`
			ConfigFlag     string `json:"configFlag"`
			UpdateDate     string `json:"updateDate"`
			CreateDate     string `json:"createDate"`
			TypeName       string `json:"typeName"`
			UserName       string `json:"userName"`
			Agent          struct {
				ID                  int    `json:"id"`
				RoleType            int    `json:"roleType"`
				LevelType           int    `json:"levelType"`
				ProfitType          int    `json:"profitType"`
				ProfitProportion    int    `json:"profitProportion"`
				FixedProfitMoney    int    `json:"fixedProfitMoney"`
				CashWithdrawalWay   int    `json:"cashWithdrawalWay"`
				SettingInfo         string `json:"settingInfo"`
				FunctionSetting     string `json:"functionSetting"`
				ParentID            int    `json:"parentId"`
				RootID              int    `json:"rootId"`
				LeftNum             int    `json:"leftNum"`
				RightNum            int    `json:"rightNum"`
				Status              int    `json:"status"`
				TotalOrderCount     int    `json:"totalOrderCount"`
				TotalOrderMoney     int    `json:"totalOrderMoney"`
				TotalProfitMoney    int    `json:"totalProfitMoney"`
				PlaceCount          int    `json:"placeCount"`
				LastPlaceChangeDate string `json:"lastPlaceChangeDate"`
				DeviceCount         int    `json:"deviceCount"`
				UpdateDate          string `json:"updateDate"`
				CreateDate          string `json:"createDate"`
				RoleTypeName        string `json:"roleTypeName"`
				AgentCount          int    `json:"agentCount"`
				HaveChild           bool   `json:"haveChild"`
				TotalProfitMoneyStr string `json:"totalProfitMoneyStr"`
				IsLeaf              bool   `json:"isLeaf"`
				IsRoot              bool   `json:"isRoot"`
			} `json:"agent,omitempty"`
			Address        string   `json:"address,omitempty"`
			Cpi            int      `json:"cpi"`
			ImgPathArray   []string `json:"imgPathArray"`
			ProfitModeName string   `json:"profitModeName"`
			Cpistr         string   `json:"cpistr"`
			DetailInfoDate struct {
				Address string `json:"address"`
			} `json:"detailInfoDate,omitempty"`
			TypeClassifyName   string `json:"typeClassifyName"`
			AuthenticationNote string `json:"authenticationNote"`
			StateName          string `json:"stateName"`
			ImgPath            string `json:"imgPath"`
		} `json:"data"`
	} `json:"body"`
}

type msgResp struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

// ----------------------------更新订单----------------------------//
func (logic *SyncLogic) UpdateOrdersLogic(page, pageSize int, cookie string) ([]string, error) {
	path := fmt.Sprintf("./data/orders/%s", time.Now().Format("20060102150405"))

	url := "http://mng.yundian.ink/mng/10041/business/order/list.data"
	err := logic.doRequestOrders(page, pageSize, url, path, cookie) // 抓取订单信息
	if err != nil {
		return nil, err
	}

	//urlUser := "http://mng.yundian.ink/takeOrder/10041/order/list.data"
	//err := logic.doRequestTakeOrders(page, pageSize, urlUser, path, cookie) // 抓取抽单信息
	//if err != nil {
	//	return nil, err
	//}

	var strs []string

	for i := 1; i <= page; i++ {
		//strUser := logic.taskOrders(i, path)
		//strs = append(strs, strUser)

		//strPlace := logic.taskOrdersTake(i, path)
		//strs = append(strs, strPlace)
	}

	return strs, nil
}
func (logic *SyncLogic) UpdateOrdersTakeLogic(page, pageSize int, cookie string) ([]string, error) {
	path := fmt.Sprintf("./data/torders/%s", time.Now().Format("20060102150405"))

	//url := "http://mng.yundian.ink/mng/10041/business/order/list.data"
	//err := logic.doRequestOrders(page, pageSize, url, path, cookie) // 抓取订单信息
	//if err != nil {
	//	return nil, err
	//}

	urlUser := "http://mng.yundian.ink/takeOrder/10041/order/list.data"
	err := logic.doRequestTakeOrders(page, pageSize, urlUser, path, cookie) // 抓取抽单信息
	if err != nil {
		return nil, err
	}

	var strs []string

	for i := 1; i <= page; i++ {
		//strUser := logic.taskOrders(i, path)
		//strs = append(strs, strUser)

		//strPlace := logic.taskOrdersTake(i, path)
		//strs = append(strs, strPlace)
	}

	return strs, nil
}
func (logic *SyncLogic) UpdateOrdersTosqlLogic(page int) ([]string, error) {
	path := fmt.Sprintf("./data/orders/%s", "20210407171522")

	var strs []string

	for i := 1; i <= page; i++ {
		strUser := logic.taskOrders(i, path)
		strs = append(strs, strUser)
	}

	return strs, nil
}

//func (logic *SyncLogic) UpdateTabkeOrdersLogic(page, pageSize int, cookie string) ([]string, error) {
//	path := fmt.Sprintf("./data/torders/%s",time.Now().Format("20060102150405"))
//
//	//url := "http://mng.yundian.ink/mng/10041/business/order/list.data"
//	//err := logic.doRequestOrders(page, pageSize, url, path, cookie) // 抓取订单信息
//	//if err != nil {
//	//	return nil, err
//	//}
//
//	urlUser := "http://mng.yundian.ink/takeOrder/10041/order/list.data"
//	err := logic.doRequestTakeOrders(page, pageSize, urlUser, path, cookie) // 抓取抽单信息
//	if err != nil {
//		return nil, err
//	}
//
//	var strs []string
//
//	for i := 1; i <= page; i++ {
//		//strUser := logic.taskOrders(i, path)
//		//strs = append(strs, strUser)
//
//		strPlace := logic.taskOrdersTake(i, path)
//		strs = append(strs, strPlace)
//	}
//
//
//	return strs, nil
//}
func (logic *SyncLogic) UpdateTakeOrdersTosqlLogic(page int) ([]string, error) {
	path := fmt.Sprintf("./data/torders/%s", "20210407171911")

	var strs []string

	for i := 1; i <= page; i++ {
		strPlace := logic.taskOrdersTake(i, path)
		strs = append(strs, strPlace)
	}

	return strs, nil
}

func (logic *SyncLogic) doRequestOrders(pages, pageSize int, url, path, cookie string) error {
	client := resty.New()
	for i := 1; i <= pages; i++ {
		m := map[string]string{}
		m["page"] = strconv.Itoa(i)
		m["limit"] = strconv.Itoa(pageSize)
		resp, err := client.R().
			SetHeader("Content-Type", "application/x-www-form-urlencoded").
			SetFormData(m).
			SetHeader("Cookie", cookie).
			Post(url)
		if err != nil {
			return err
		}
		msg := new(msgResp)
		_ = json.Unmarshal(resp.Body(), &msg)
		if msg.Msg != "" {
			return errors.New(msg.Msg)
		}
		// 创建
		err = helper.MakeDir(path)
		if err != nil {
			return err
		}
		err = ioutil.WriteFile(path+fmt.Sprintf("/orders-%d.json", i), resp.Body(), 666)
		if err != nil {
			return err
		}
	}
	return nil
}

func (logic *SyncLogic) doRequestTakeOrders(pages, pageSize int, url, path, cookie string) error {
	client := resty.New()
	for i := 1; i <= pages; i++ {
		m := map[string]string{}
		m["page"] = strconv.Itoa(i)
		m["limit"] = strconv.Itoa(pageSize)
		resp, err := client.R().
			SetHeader("Content-Type", "application/x-www-form-urlencoded").
			SetFormData(m).
			SetHeader("Cookie", cookie).
			Post(url)
		if err != nil {
			return err
		}
		msg := new(msgResp)
		_ = json.Unmarshal(resp.Body(), &msg)
		if msg.Msg != "" {
			return errors.New(msg.Msg)
		}
		// 创建
		err = helper.MakeDir(path)
		if err != nil {
			return err
		}
		err = ioutil.WriteFile(path+fmt.Sprintf("/takeorders-%d.json", i), resp.Body(), 666)
		if err != nil {
			return err
		}
	}
	return nil
}

func (logic *SyncLogic) taskOrders(i int, path string) string {
	lists := new(orderGenerated)
	viper.SetConfigFile(path + fmt.Sprintf("/orders-%d.json", i))
	if err := viper.ReadInConfig(); err != nil {
		log.Fatal("viper.ReadInConfig failed : ", err.Error())
	}
	// 反序列化到struct
	if err := viper.Unmarshal(lists); err != nil {
		log.Fatal("viper.Unmarshal failed : ", err.Error())
	}

	// 写入数据库
	var ucount, ccount int
	for _, lst := range lists.Body.Data {
		var tradeState, tradeStateDesc, desc string
		switch lst.State {
		case 1:
			tradeState = "CREATED" // CREATED 商户已创建服务订单
			tradeStateDesc = "商户已创建服务订单"
		case 2:
			tradeState = "DOING" // DOING 服务订单进行中
			tradeStateDesc = "服务订单进行中"
			desc = "USER_CONFIRM"
		case 5:
			tradeState = "DONE"
			tradeStateDesc = "服务订单完成" // DONE 服务订单完成
			desc = "COMPLETE"
		case 3:
			tradeState = "REVOKED"
			tradeStateDesc = "商户取消服务订单" // REVOKED 商户取消服务订单
		case 4:
			tradeState = "EXPIRED" // EXPIRED 服务订单已失效
			tradeStateDesc = "服务订单已失效"
		}

		var payFrom int8
		if lst.TradeType == "Normal" {
			payFrom = 2
		}
		if lst.TradeType == "PreAuthPay" {
			payFrom = 1
		}

		m := orders.New()
		m.Appid = lst.AppID
		m.Mchid = "1600369044"

		m.TradeNo = lst.TradeNo
		m.OutTradeNo = lst.ExternalTradeNo
		m.TradeType = lst.TradeType
		m.TradeState = tradeState
		m.TradeStateDesc = tradeStateDesc
		m.TradeStateDoing = desc
		m.State = int8(lst.State)

		m.Title = lst.Title

		m.DeviceSn = lst.DeviceSn
		m.SharedMode = lst.SharedMode
		if lst.FeeMode == 2 {
			m.FeeMode = 1
		} else {
			m.FeeMode = 2
		}

		m.Money = int64(lst.Money)
		m.MoneyStr = lst.MoneyStr
		m.PayMoney = int64(lst.PayMoney)
		m.PayMoneyStr = lst.PayMoneyStr
		m.SettlementWay = int8(lst.SettlementWay)
		m.SettlementMoney = int64(lst.SettlementMoney)
		m.SettlementMoneyStr = lst.SettlementMoneyStr
		m.SettlementState = int8(lst.SettlementState)

		m.CouponType = int8(lst.CouponType)
		m.CouponMoney = int64(lst.CouponMoney)
		m.CouponMoneyStr = lst.CouponMoneyStr

		m.OrderFrom = "weixin"
		m.PayType = int8(lst.PayType) // 3 微信支付
		m.PayFrom = payFrom

		m.PlaceId = lst.PlaceID
		m.PlaceName = lst.PlaceName
		m.MemberId = lst.MemberID
		m.MemberName = lst.MemberName
		if lst.PlaceUserID == 100000 {
			m.UserId = 2
		} else {
			m.UserId = lst.PlaceUserID
		}

		m.UserName = lst.PlaceUserName

		m.OvertimeState = int8(lst.OvertimeState)
		m.IsDelete = 0
		m.IsDraw = 0

		m.CreateAt = dingo.Time(wechatpay.StrTimeToInt(lst.CreateDate))
		m.UpdateAt = dingo.Time(wechatpay.StrTimeToInt(lst.UpdateDate))
		m.PayAt = dingo.Time(wechatpay.StrTimeToInt(lst.CreateDate))
		m.EndAt = dingo.Time(wechatpay.StrTimeToInt(lst.UpdateDate))

		m.ProductId = lst.ProductID
		userInfo := dao.NewUserDao().GetUserInfoById(lst.PlaceUserID).Unwrap().(*users.UserModel)
		m.ParentId = userInfo.ParentID
		m.IsTianHai = 1

		m.RefundMoney = int64(lst.RefundMoney)
		// 查询 库中是否存在此数据
		ccount++
		global.Orm.Table("orders1").Create(m)
		//var count int64
		//global.Orm.Table("orders").
		//	Where("is_draw = ?", 0).
		//	Where("trade_no = ?", lst.TradeNo).
		//	Where("out_trade_no = ?", lst.ExternalTradeNo).
		//	Where("create_at = ?", dingo.Time(wechatpay.StrTimeToInt(lst.CreateDate))).
		//	Count(&count)
		//log.Println(count)
		//if count > 0 {
		//	ucount++
		//	global.Orm.Table("orders").
		//		Where("is_draw = ?", 0).
		//		Where("trade_no = ?", m.TradeNo).
		//		Where("out_trade_no = ?", m.OutTradeNo).
		//		Where("create_at = ?", dingo.Time(wechatpay.StrTimeToInt(lst.CreateDate))).
		//		Model(&m).Updates(m)
		//} else {
		//	ccount++
		//	log.Println(lst.CreateDate)
		//	global.Orm.Table("orders").Create(m)
		//}
	}
	//fmt.Printf("当前页-%d,新增%d条,更新%d条 \n", i, ccount, ucount)
	str := fmt.Sprintf("当前页面%d, 更新成功%d条，新增成功%d条 \n", i, ucount, ccount)
	return str
}

func (logic *SyncLogic) taskOrdersTake(i int, path string) string {
	lists := new(orderTakeGenerated)
	viper.SetConfigFile(path + fmt.Sprintf("/takeorders-%d.json", i))
	if err := viper.ReadInConfig(); err != nil {
		log.Fatal("viper.ReadInConfig failed : ", err.Error())
	}
	// 反序列化到struct
	if err := viper.Unmarshal(lists); err != nil {
		log.Fatal("viper.Unmarshal failed : ", err.Error())
	}

	// 写入数据库
	var ucount, ccount int
	for _, lst := range lists.Body.Data {
		var tradeState, tradeStateDesc, desc string
		switch lst.State {
		case 1:
			tradeState = "CREATED" // CREATED 商户已创建服务订单
			tradeStateDesc = "商户已创建服务订单"
		case 2:
			tradeState = "DOING" // DOING 服务订单进行中
			tradeStateDesc = "服务订单进行中"
			desc = "USER_CONFIRM"
		case 5:
			tradeState = "DONE"
			tradeStateDesc = "服务订单完成" // DONE 服务订单完成
			desc = "MCH_COMPLETE"
		case 3:
			tradeState = "REVOKED"
			tradeStateDesc = "商户取消服务订单" // REVOKED 商户取消服务订单
		case 4:
			tradeState = "EXPIRED" // EXPIRED 服务订单已失效
			tradeStateDesc = "服务订单已失效"
		}

		var payFrom int8
		if lst.TradeType == "Normal" {
			payFrom = 2
		}
		if lst.TradeType == "PreAuthPay" {
			payFrom = 1
		}

		//m := &orders.OrderTakeModel{}
		m := orders.New()
		m.Appid = lst.AppID
		m.Mchid = "1600369044"

		m.TradeNo = lst.TradeNo
		m.OutTradeNo = lst.ExternalTradeNo
		m.TradeType = lst.TradeType
		m.TradeState = tradeState
		m.TradeStateDesc = tradeStateDesc
		m.TradeStateDoing = desc
		m.State = int8(lst.State)

		m.Title = lst.Title

		m.DeviceSn = lst.DeviceSn
		m.SharedMode = lst.SharedMode
		if lst.FeeMode == 2 {
			m.FeeMode = 1
		} else {
			m.FeeMode = 2
		}

		m.Money = int64(lst.Money)
		m.MoneyStr = lst.MoneyStr
		m.PayMoney = int64(lst.PayMoney)
		m.PayMoneyStr = lst.PayMoneyStr
		m.SettlementWay = int8(lst.SettlementWay)
		m.SettlementMoney = int64(lst.SettlementMoney)
		m.SettlementMoneyStr = lst.SettlementMoneyStr
		m.SettlementState = int8(lst.SettlementState)
		m.RefundMoney = int64(lst.RefundMoney)

		m.CouponType = 1
		m.CouponMoney = int64(lst.CouponMoney)
		m.CouponMoneyStr = lst.CouponMoneyStr

		m.OrderFrom = "weixin"
		m.PayType = int8(lst.PayType) // 3 微信支付
		m.PayFrom = payFrom

		m.PlaceId = lst.PlaceID
		m.PlaceName = lst.PlaceName
		m.MemberId = lst.MemberID
		m.MemberName = lst.MemberName
		if lst.PlaceUserID == 100000 {
			m.UserId = 2
		} else {
			m.UserId = lst.PlaceUserID
		}
		m.UserName = lst.PlaceUserName

		m.OvertimeState = int8(lst.OvertimeState)
		m.IsDelete = 0
		m.IsDraw = 1

		m.CreateAt = dingo.Time(wechatpay.StrTimeToInt(lst.CreateDate))
		m.UpdateAt = dingo.Time(wechatpay.StrTimeToInt(lst.UpdateDate))
		m.DrawAt = dingo.Time(wechatpay.StrTimeToInt(lst.CreateDate))
		m.PayAt = dingo.Time(wechatpay.StrTimeToInt(lst.CreateDate))
		m.EndAt = dingo.Time(wechatpay.StrTimeToInt(lst.UpdateDate))

		userInfo := dao.NewUserDao().GetUserInfoById(lst.PlaceUserID).Unwrap().(*users.UserModel)
		m.ParentId = userInfo.ParentID
		m.ProductId = lst.ProductID
		m.IsTianHai = 1

		m.RefundMoney = int64(lst.RefundMoney)

		ccount++
		global.Orm.Table("orders2").Create(m)
		//var count int64
		//global.Orm.Table("orders").
		//	Where("is_draw = ?", 1).
		//	Where("trade_no = ?", m.TradeNo).
		//	Where("out_trade_no = ?", m.OutTradeNo).
		//	Where("create_at = ?", dingo.Time(wechatpay.StrTimeToInt(lst.CreateDate))).
		//	Count(&count)
		//if count > 0 {
		//	ucount++
		//	global.Orm.Table("orders").
		//		Where("is_draw = ?", 1).
		//		Where("trade_no = ?", m.TradeNo).
		//		Where("out_trade_no = ?", m.OutTradeNo).
		//		Where("create_at = ?", dingo.Time(wechatpay.StrTimeToInt(lst.CreateDate))).
		//		Model(&m).Updates(m)
		//} else {
		//	ccount++
		//	global.Orm.Table("orders").Create(m)
		//}
	}
	//fmt.Printf("当前页-%d,新增%d条,更新%d条 \n", i, ccount, ucount)
	str := fmt.Sprintf("当前页面%d, 更新成功%d条，新增成功%d条 \n", i, ucount, ccount)
	return str
}

type orderGenerated struct {
	Body struct {
		Total int `json:"total"`
		Data  []struct {
			TradeNo             string  `json:"tradeNo"`
			Title               string  `json:"title"`
			ProjectID           int     `json:"projectId"`
			AppID               string  `json:"appId"`
			SharedMode          string  `json:"sharedMode"`
			FeeMode             int     `json:"feeMode"`
			MemberID            string  `json:"memberId"`
			MemberName          string  `json:"memberName"`
			Money               int     `json:"money"`
			PayType             int     `json:"payType"`
			TradeType           string  `json:"tradeType"`
			CouponType          int     `json:"couponType"`
			CouponMoney         int     `json:"couponMoney"`
			PayMoney            int     `json:"payMoney,omitempty"`
			RefundMoney         int     `json:"refundMoney"`
			SettlementWay       int     `json:"settlementWay"`
			SettlementMoney     int     `json:"settlementMoney"`
			SettlementState     int     `json:"settlementState"`
			PlaceID             int     `json:"placeId"`
			PlaceUserID         int     `json:"placeUserId"`
			PlaceName           string  `json:"placeName"`
			PlaceUserName       string  `json:"placeUserName"`
			PlaceImgPath        string  `json:"placeImgPath"`
			DeviceSn            string  `json:"deviceSn"`
			DeviceTypeID        int     `json:"deviceTypeId"`
			ProductID           string  `json:"productId"`
			OvertimeState       int     `json:"overtimeState"`
			State               int     `json:"state"`
			DelFlag             bool    `json:"delFlag"`
			UpdateDate          string  `json:"updateDate"`
			CreateDate          string  `json:"createDate"`
			ExternalTradeNo     string  `json:"externalTradeNo"`
			MoneyStr            string  `json:"moneyStr"`
			PayTypeName         string  `json:"payTypeName"`
			SharedModeName      string  `json:"sharedModeName"`
			StateName           string  `json:"stateName"`
			FeeModeName         string  `json:"feeModeName"`
			SettlementStateName string  `json:"settlementStateName"`
			PayMoneyStr         string  `json:"payMoneyStr"`
			Price               float64 `json:"price"`
			OvertimeStateName   string  `json:"overtimeStateName"`
			CouponTypeName      string  `json:"couponTypeName"`
			SettlementMoneyStr  string  `json:"settlementMoneyStr"`
			CouponMoneyStr      string  `json:"couponMoneyStr"`
			TradeState          int     `json:"tradeState"`
			Province            string  `json:"province,omitempty"`
			City                string  `json:"city,omitempty"`
			Agent               struct {
				ID               int    `json:"id"`
				RoleType         int    `json:"roleType"`
				LevelType        int    `json:"levelType"`
				Status           int    `json:"status"`
				ProfitType       int    `json:"profitType"`
				ProfitProportion int    `json:"profitProportion"`
				WxIncomeQrcode   string `json:"wxIncomeQrcode"`
				AgentChildCount  int    `json:"agentChildCount"`
				PlaceCount       int    `json:"placeCount"`
				DeviceCount      int    `json:"deviceCount"`
				SettingInfo      string `json:"settingInfo"`
				FunctionSetting  string `json:"functionSetting"`
				ParentID         int    `json:"parentId"`
				RootID           int    `json:"rootId"`
				LeftNum          int    `json:"leftNum"`
				RightNum         int    `json:"rightNum"`
				UpdateDate       string `json:"updateDate"`
				CreateDate       string `json:"createDate"`
				UserID           int    `json:"userId"`
				IsMain           bool   `json:"isMain"`
				RoleTypeName     string `json:"roleTypeName"`
				AgentCount       int    `json:"agentCount"`
				HaveChild        bool   `json:"haveChild"`
				IsLeaf           bool   `json:"isLeaf"`
				IsRoot           bool   `json:"isRoot"`
			} `json:"agent,omitempty"`
		} `json:"data"`
	} `json:"body"`
}

type orderTakeGenerated struct {
	Body struct {
		Total int `json:"total"`
		Data  []struct {
			TradeNo             string `json:"tradeNo"`
			ExternalTradeNo     string `json:"externalTradeNo"`
			ProjectID           int    `json:"projectId"`
			AppID               string `json:"appId"`
			Title               string `json:"title"`
			MemberID            string `json:"memberId"`
			MemberName          string `json:"memberName"`
			Money               int    `json:"money"`
			PayType             int    `json:"payType"`
			TradeType           string `json:"tradeType"`
			FeeMode             int    `json:"feeMode"`
			CouponMoney         int    `json:"couponMoney"`
			SettlementWay       int    `json:"settlementWay"`
			SettlementMoney     int    `json:"settlementMoney"`
			SettlementState     int    `json:"settlementState"`
			PlaceID             int    `json:"placeId"`
			PlaceUserID         int    `json:"placeUserId"`
			PlaceName           string `json:"placeName"`
			PlaceUserName       string `json:"placeUserName"`
			PlaceImgPath        string `json:"placeImgPath"`
			DeviceSn            string `json:"deviceSn"`
			DeviceTypeID        int    `json:"deviceTypeId"`
			SharedMode          string `json:"sharedMode"`
			ProductID           string `json:"productId"`
			OvertimeState       int    `json:"overtimeState"`
			State               int    `json:"state"`
			DelFlag             bool   `json:"delFlag"`
			UpdateDate          string `json:"updateDate"`
			CreateDate          string `json:"createDate"`
			Price               int    `json:"price"`
			PayTypeName         string `json:"payTypeName"`
			PayMoneyStr         string `json:"payMoneyStr"`
			SharedModeName      string `json:"sharedModeName"`
			StateName           string `json:"stateName"`
			FeeModeName         string `json:"feeModeName"`
			CouponMoneyStr      string `json:"couponMoneyStr"`
			OvertimeStateName   string `json:"overtimeStateName"`
			SettlementStateName string `json:"settlementStateName"`
			SettlementMoneyStr  string `json:"settlementMoneyStr"`
			MoneyStr            string `json:"moneyStr"`
			TradeState          int    `json:"tradeState"`
			PayMoney            int    `json:"payMoney,omitempty"`
			RefundMoney         int    `json:"refundMoney,omitempty"`
			Agent               struct {
				ID               int    `json:"id"`
				RoleType         int    `json:"roleType"`
				LevelType        int    `json:"levelType"`
				Status           int    `json:"status"`
				ProfitType       int    `json:"profitType"`
				ProfitProportion int    `json:"profitProportion"`
				WxIncomeQrcode   string `json:"wxIncomeQrcode"`
				AgentChildCount  int    `json:"agentChildCount"`
				PlaceCount       int    `json:"placeCount"`
				DeviceCount      int    `json:"deviceCount"`
				SettingInfo      string `json:"settingInfo"`
				FunctionSetting  string `json:"functionSetting"`
				ParentID         int    `json:"parentId"`
				RootID           int    `json:"rootId"`
				LeftNum          int    `json:"leftNum"`
				RightNum         int    `json:"rightNum"`
				UpdateDate       string `json:"updateDate"`
				CreateDate       string `json:"createDate"`
				UserID           int    `json:"userId"`
				RoleTypeName     string `json:"roleTypeName"`
				AgentCount       int    `json:"agentCount"`
				HaveChild        bool   `json:"haveChild"`
				IsMain           bool   `json:"isMain"`
				IsLeaf           bool   `json:"isLeaf"`
				IsRoot           bool   `json:"isRoot"`
			} `json:"agent,omitempty"`
		} `json:"data"`
	} `json:"body"`
}

// ----------------------------更新设备----------------------------//

func (logic *SyncLogic) UpdateDeviceLogic(page, pageSize int, cookie string) ([]string, error) {
	path := fmt.Sprintf("./data/devices/%s", time.Now().Format("20060102150405"))
	url := "http://mng.cnman.cn/mng/10082/dev/pcl/list.data"
	// 抓取
	err := logic.doRequestDevices(page, pageSize, url, path, cookie) // 抓取订单信息
	if err != nil {
		return nil, err
	}

	//path := "./data/devices/20210315141025" // 数据已抓取时，用这个

	var strs []string
	//for i := 1; i <= page; i++ {
	//	strDevice := logic.taskDevices(i, path)
	//	strs = append(strs, strDevice)
	//}

	return strs, nil
}
func (logic *SyncLogic) UpdateYCDeviceLogic(page, pageSize int, cookie string) ([]string, error) {
	path := fmt.Sprintf("./data/devices/%s", time.Now().Format("20060102150405"))
	url := "http://mng.kdcgx.com/mng/10032/dev/pcl/list.data"
	// 抓取
	err := logic.doRequestDevices(page, pageSize, url, path, cookie) // 抓取订单信息
	if err != nil {
		return nil, err
	}

	//path := "./data/devices/20210315141025" // 数据已抓取时，用这个

	var strs []string
	//for i := 1; i <= page; i++ {
	//	strDevice := logic.taskDevices(i, path)
	//	strs = append(strs, strDevice)
	//}

	return strs, nil
}

func (logic *SyncLogic) doRequestDevices(pages, pageSize int, url, path, cookie string) error {
	client := resty.New()
	for i := 1; i <= pages; i++ {
		m := map[string]string{}
		m["page"] = strconv.Itoa(i)
		m["limit"] = strconv.Itoa(pageSize)
		resp, err := client.R().
			SetHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8").
			SetFormData(m).
			SetHeader("Cookie", cookie).
			Post(url)
		if err != nil {
			return err
		}
		msg := new(msgResp)
		_ = json.Unmarshal(resp.Body(), &msg)
		if msg.Code != 200 && msg.Msg != "" {
			return errors.New(msg.Msg)
		}
		// 创建
		err = helper.MakeDir(path)
		if err != nil {
			return err
		}
		err = ioutil.WriteFile(path+fmt.Sprintf("/%d.json", i), resp.Body(), 666)
		if err != nil {
			return err
		}
	}
	return nil
}

func (logic *SyncLogic) taskDevices(i int, path string) string {
	lists := new(DevicesGenerated)
	viper.SetConfigFile(path + fmt.Sprintf("/%d.json", i))
	if err := viper.ReadInConfig(); err != nil {
		log.Fatal("viper.ReadInConfig failed : ", err.Error())
	}
	// 反序列化到struct
	if err := viper.Unmarshal(lists); err != nil {
		log.Fatal("viper.Unmarshal failed : ", err.Error())
	}

	// 写入数据库
	var ucount, ccount int
	for _, lst := range lists.Body.Data {
		m := devices.New()
		s := string([]byte(lst.DeviceSn)[:5])
		if s == "831YD" || s == "830YD" { // 最早一批线
			//m.Url = string(2)
		} else { // dev.yundian.ink
			//m.Url = string(1)
		}

		// 批号  序号
		deviceSns := strings.Split(lst.DeviceSn, "YD")
		if len(deviceSns) >= 2 {
			preSn := utils.Join(deviceSns[0], "YD")
			sn, _ := strconv.Atoi(deviceSns[1])
			m.PreSn = preSn
			m.Sn = sn
		} else {
			log.Println(lst.DeviceSn)
		}
		m.DeviceSn = lst.DeviceSn

		m.DeviceTypeName = lst.DeviceTypeName // 设备类型名
		m.DeviceTypeId = lst.DeviceTypeID     // 设备类型ID
		m.PwdIndex = 1
		m.PwdSecretKey = lst.PwdSecretKey
		m.PwdDecodeType = lst.PwdDecodeType
		m.State = uint8(lst.State)
		m.SharedMode = lst.SharedMode // 共享模型
		if lst.DeviceTypeID == 12 {
			m.FeeMode = 2 // 2套餐
		} else {
			m.FeeMode = 1 // 1计时
		}
		m.UseCount = lst.UseCount

		m.PlaceId = lst.PlaceID
		m.PlaceName = lst.PlaceName
		// 代理商id 与 代理商name  后期用户与商户稳定后，再修改
		m.AgentUserId = 2
		m.AgentUserName = "昀电"

		m.CreateAt = dingo.Time(wechatpay.StrTimeToInt(lst.CreateDate))
		m.UpdateAt = dingo.Time(wechatpay.StrTimeToInt(lst.UpdateDate))
		if lst.DeployDate != "" {
			m.DeployAt = dingo.Time(wechatpay.StrTimeToInt(lst.DeployDate))
		}

		// 查询 库中是否存在此数据
		var count int64
		global.Orm.Table("devices").Where("device_sn = ?", m.DeviceSn).Count(&count)
		if count > 0 {
			ucount++
			global.Orm.Table("devices").Where("device_sn = ?", m.DeviceSn).Model(&m).Updates(m)
		} else {
			ccount++
			global.Orm.Table("devices").Create(m)
		}

	}
	str := fmt.Sprintf("当前页-%d,新增%d条,更新%d条 \n", i, ccount, ucount)
	return str
}

type DevicesGenerated struct {
	Code int `json:"code"`
	Body struct {
		Total int `json:"total"`
		Data  []struct {
			DeviceSn          string `json:"deviceSn"`
			PlaceID           int    `json:"placeId,omitempty"`
			DeviceTypeID      int    `json:"deviceTypeId"`
			PwdIndex          int    `json:"pwdIndex"`
			PwdDecodeType     string `json:"pwdDecodeType"`
			PwdSecretKey      string `json:"pwdSecretKey"`
			CurrentTradeNo    string `json:"currentTradeNo,omitempty"`
			CurrentTradeState int    `json:"currentTradeState"`
			UseCount          int    `json:"useCount"`
			State             int    `json:"state"`
			DeployDate        string `json:"deployDate,omitempty"`
			UpdateDate        string `json:"updateDate"`
			CreateDate        string `json:"createDate"`
			DeviceType        struct {
				ID               int      `json:"id"`
				DeviceModelID    string   `json:"deviceModelId"`
				Name             string   `json:"name"`
				ImgPaths         string   `json:"imgPaths"`
				NetworkTypes     string   `json:"networkTypes"`
				SharedMode       string   `json:"sharedMode"`
				Type             int      `json:"type"`
				FeeMode          int      `json:"feeMode"`
				State            int      `json:"state"`
				UpdateDate       string   `json:"updateDate"`
				CreateDate       string   `json:"createDate"`
				PwdDecodeType    string   `json:"pwdDecodeType"`
				SecretKey        string   `json:"secretKey"`
				SharedModeName   string   `json:"sharedModeName"`
				StateName        string   `json:"stateName"`
				ImgPathArray     []string `json:"imgPathArray"`
				NetworkTypeNames string   `json:"networkTypeNames"`
				FeeModeName      string   `json:"feeModeName"`
				ImgPath          string   `json:"imgPath"`
			} `json:"deviceType"`
			PlaceName      string `json:"placeName,omitempty"`
			SharedModeName string `json:"sharedModeName"`
			SharedMode     string `json:"sharedMode"`
			FeeMode        int    `json:"feeMode"`
			DeviceTypeName string `json:"deviceTypeName"`
			StateName      string `json:"stateName"`
		} `json:"data"`
	} `json:"body"`
}

// ----------------------------更新分红日志----------------------------//

func (logic *SyncLogic) UpdateDividendsLogic(page, pageSize int, cookie string) ([]string, error) {
	path := fmt.Sprintf("./data/dividends/%s", time.Now().Format("20060102150405"))
	url := "http://mng.yundian.ink/mng/10041/user/agent/settlement/orderItem/list.data"

	var user []users.UserModel
	global.Orm.Table("users").Find(&user)
	for _, u := range user {
		// 抓取
		err := logic.doRequestDividends(page, pageSize, u.ID, url, path, cookie) // 抓取订单信息
		if err != nil {
			return nil, err
		}
	}

	var strs []string
	//for _,u := range user {
	//	for i := 1; i <= page; i++ {
	//		strDividends := logic.taskDividends(i, path, u)
	//		strs = append(strs, strDividends)
	//	}
	//}

	return strs, nil
}

func (logic *SyncLogic) doRequestDividends(pages, pageSize, id int, url, path, cookie string) error {
	userId := strconv.Itoa(id)
	client := resty.New()
	for i := 1; i <= pages; i++ {
		m := map[string]string{}
		m["page"] = strconv.Itoa(i)
		m["limit"] = strconv.Itoa(pageSize)
		m["userId"] = userId // 用户ID
		resp, err := client.R().
			SetHeader("Content-Type", "application/x-www-form-urlencoded").
			SetFormData(m).
			SetHeader("Cookie", cookie).
			Post(url)
		if err != nil {
			return err
		}
		msg := new(msgResp)
		_ = json.Unmarshal(resp.Body(), &msg)
		if msg.Code != 200 && msg.Msg != "" {
			return errors.New(msg.Msg)
		}
		// 创建
		err = helper.MakeDir(path)
		if err != nil {
			return err
		}
		err = ioutil.WriteFile(path+fmt.Sprintf("/%s-%d.json", userId, i), resp.Body(), 666)
		if err != nil {
			return err
		}
	}
	return nil
}

func (logic *SyncLogic) taskDividends(i int, path string, um users.UserModel) string {
	lists := new(settLogGenerated)
	viper.SetConfigFile(path + fmt.Sprintf("/%d-%d.json", um.ID, i))
	if err := viper.ReadInConfig(); err != nil {
		log.Fatal("viper.ReadInConfig failed : ", err.Error())
	}
	// 反序列化到struct
	if err := viper.Unmarshal(lists); err != nil {
		log.Fatal("viper.Unmarshal failed : ", err.Error())
	}

	var ccount, ucount int
	if len(lists.Body.Data) > 0 {
		for _, lst := range lists.Body.Data {
			orderInfo := orders.New()
			global.Orm.Table("orders").Where("trade_no = ?", lst.TradeNo).Find(orderInfo)

			m := dividendslog.New()
			m.Id = lst.ID
			m.TradeNo = lst.TradeNo

			m.Money = int64(lst.Money)
			m.MoneyStr = lst.MoneyStr
			m.PayMoney = orderInfo.PayMoney
			m.PayMoneyStr = orderInfo.PayMoneyStr
			m.SettlementMoney = int64(lst.SettlementMoney)
			m.SettlementMoneyStr = lst.SettlementMoneyStr

			m.ProfitType = int8(lst.ProfitType)
			m.ProfitProportion = int8(lst.ProfitProportion)

			m.DeviceSn = lst.DeviceSn
			m.SharedMode = lst.SharedMode
			m.FeeMode = int8(lst.FeeMode)
			m.DeviceTypeID = lst.DeviceTypeID
			m.DeviceTypeName = lst.DeviceTypeName

			m.UserId = lst.UserID
			m.UserName = lst.UserName
			m.PlaceId = lst.PlaceID
			m.PlaceName = lst.PlaceName
			m.MemberId = orderInfo.MemberId
			m.MemberName = orderInfo.MemberName

			m.State = int8(lst.State)

			m.CreateAt = dingo.Time(wechatpay.StrTimeToInt(lst.CreateDate))
			m.UpdateAt = dingo.Time(wechatpay.StrTimeToInt(lst.UpdateDate))

			var count int64
			global.Orm.Table("dividends_log").
				Where("trade_no = ?", lst.TradeNo).
				Where("user_id = ?", lst.UserID).
				Where("place_id = ?", lst.PlaceID).Count(&count)
			if count > 0 {
				ucount++
				global.Orm.Table("dividends_log").Where("trade_no = ?", lst.TradeNo).
					Where("user_id = ?", lst.UserID).
					Where("place_id = ?", lst.PlaceID).Model(&m).Updates(m)
			} else {
				ccount++
				global.Orm.Table("dividends_log").Create(m) //新增
			}
		}
		str := fmt.Sprintf("用户:%s(%d)当前页-%d,新增%d条,更新%d条 \n", um.Name, um.ID, i, ccount, ucount)
		return str
	}
	str := fmt.Sprintf("用户:%s(%d)当前页-%d,新增%d条,更新%d条 \n", um.Name, um.ID, i, ccount, ucount)
	return str
}

type settLogGenerated struct {
	Code int `json:"code"`
	Body struct {
		Total int `json:"total"`
		Data  []struct {
			ID                 int     `json:"id"`
			TradeNo            string  `json:"tradeNo"`
			UserID             int     `json:"userId"`
			UserName           string  `json:"userName"`
			PlaceID            int     `json:"placeId"`
			PlaceName          string  `json:"placeName"`
			DeviceSn           string  `json:"deviceSn"`
			SharedMode         string  `json:"sharedMode"`
			FeeMode            int     `json:"feeMode"`
			DeviceTypeID       int     `json:"deviceTypeId"`
			DeviceTypeName     string  `json:"deviceTypeName"`
			RoleType           int     `json:"roleType"`
			ProfitType         int     `json:"profitType"`
			ProfitProportion   int     `json:"profitProportion"`
			Money              float64 `json:"money"`
			SettlementMoney    int     `json:"settlementMoney"`
			State              int     `json:"state"`
			UpdateDate         string  `json:"updateDate"`
			CreateDate         string  `json:"createDate"`
			MoneyStr           string  `json:"moneyStr"`
			ProfitTypeName     string  `json:"profitTypeName"`
			SettlementMoneyStr string  `json:"settlementMoneyStr"`
			WalletType         int     `json:"walletType"`
			RoleTypeName       string  `json:"roleTypeName"`
		} `json:"data"`
	} `json:"body"`
}

// ----------------------------更新提现----------------------------//

func (logic *SyncLogic) UpdateCashLogic(page, pageSize int, cookie string) ([]string, error) {
	path := fmt.Sprintf("./data/cash/%s", time.Now().Format("20060102150405"))
	url := "http://mng.yundian.ink/mng/10041/business/cashWithdrawal/agent/list.data"

	// 抓取
	err := logic.doRequestCash(page, pageSize, url, path, cookie)
	if err != nil {
		return nil, err
	}

	var strs []string
	for i := 1; i <= page; i++ {
		strCash := logic.taskCash(i, path)
		strs = append(strs, strCash)
	}

	return strs, nil
}

func (logic *SyncLogic) doRequestCash(pages, pageSize int, url, path, cookie string) error {
	client := resty.New()
	for i := 1; i <= pages; i++ {
		m := map[string]string{}
		m["page"] = strconv.Itoa(i)
		m["limit"] = strconv.Itoa(pageSize)
		resp, err := client.R().
			SetHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8").
			SetFormData(m).
			SetHeader("Cookie", cookie).
			Post(url)
		if err != nil {
			return err
		}
		msg := new(msgResp)
		_ = json.Unmarshal(resp.Body(), &msg)
		if msg.Code != 200 && msg.Msg != "" {
			return errors.New(msg.Msg)
		}
		// 创建
		err = helper.MakeDir(path)
		if err != nil {
			return err
		}
		err = ioutil.WriteFile(path+fmt.Sprintf("/%d.json", i), resp.Body(), 666)
		if err != nil {
			return err
		}
	}
	return nil
}

func (logic *SyncLogic) taskCash(i int, path string) string {
	lists := new(agentWithDrawalGenerated)
	viper.SetConfigFile(path + fmt.Sprintf("/%d.json", i))
	if err := viper.ReadInConfig(); err != nil {
		log.Fatal("viper.ReadInConfig failed : ", err.Error())
	}
	// 反序列化到struct
	if err := viper.Unmarshal(lists); err != nil {
		log.Fatal("viper.Unmarshal failed : ", err.Error())
	}

	// 写入数据库
	var ucount, ccount int
	for _, lst := range lists.Body.Data {

		m := cashlog.New()
		m.UserID = lst.UserID
		m.State = uint8(lst.State)
		m.UpdateAt = dingo.Time(wechatpay.StrTimeToInt(lst.UpdateDate))
		m.CreateAt = dingo.Time(wechatpay.StrTimeToInt(lst.CreateDate))
		m.TradeNo = lst.TradeNo
		m.OutTradeNo = ""
		m.Money = int64(lst.Money)
		m.Appid = lst.AppID
		m.MoneyStr = lst.MoneyStr
		m.OperateAt = dingo.Time(wechatpay.StrTimeToInt(lst.OperateDate))
		m.OperateNote = lst.OperateNote
		m.ReceivingAccount = lst.ReceivingAccount
		m.ReceivingType = uint8(lst.ReceivingType)
		m.ServiceCharge = uint8(lst.ServiceChargePercentage)
		m.TransferMoney = int64(lst.TransferMoney)
		m.TransferMoneyStr = lst.TransferMoneyStr
		m.TransferType = uint8(lst.TransferType)
		m.VerifyStatus = uint8(lst.VerifyStatus)

		tm := &cashlog.TransferOrder{}
		tm.TransferType = lst.TransferOrder.TransferType
		tm.ReceivingType = lst.TransferOrder.ReceivingType
		tm.ReceivingInfo = lst.TransferOrder.ReceivingInfo
		tm.Money = int64(lst.TransferOrder.Money)
		tm.TradeNo = lst.TransferOrder.TradeNo
		tm.State = lst.TransferOrder.State
		tm.UserID = lst.TransferOrder.UserID
		tm.BusinessType = lst.TransferOrder.BusinessType
		tm.Note = lst.TransferOrder.Note
		tm.PayeeID = lst.TransferOrder.PayeeID
		tm.PayeeType = lst.TransferOrder.PayeeType
		tm.WxAppID = lst.TransferOrder.WxAppID
		tm.WxOpenID = lst.TransferOrder.WxOpenID
		m.TID = lst.ID

		tm.UpdateAt = dingo.Time(wechatpay.StrTimeToInt(lst.TransferOrder.UpdateDate))
		tm.CreateAt = dingo.Time(wechatpay.StrTimeToInt(lst.TransferOrder.CreateDate))

		// 查询 库中是否存在此数据
		var count int64
		global.Orm.Table("cash_log").Where("tid = ?", lst.ID).Count(&count)
		if count > 0 {
			ucount++
			global.Orm.Table("cash_log").Where("tid = ?", lst.ID).Model(&m).Updates(m)
		} else { // 新增
			ccount++
			global.Orm.Table("cash_log").Create(m)
		}
	}
	str := fmt.Sprintf("当前页-%d,新增%d条,更新%d条 \n", i, ccount, ucount)
	return str
}

type agentWithDrawalGenerated struct {
	Body struct {
		Total int `json:"total"`
		Data  []struct {
			ID                      int    `json:"id"`                      // 自增ID 1044
			ProjectID               int    `json:"projectId"`               // 10041 项目ID
			AppID                   string `json:"appId"`                   // 公众号Appid wxac3043809b020884
			TradeNo                 string `json:"tradeNo"`                 // 订单号 1608786614252
			UserID                  int    `json:"userId"`                  // 用户ID 100139
			Money                   int    `json:"money"`                   // 申请金额 5000   (50元)
			TransferMoney           int    `json:"transferMoney"`           // 转帐金额 5000   (50元)
			ServiceChargePercentage int    `json:"serviceChargePercentage"` // 转帐手续费 百分比
			CloudPay                bool   `json:"cloudPay"`
			HandleType              int    `json:"handleType"`
			TransferType            int    `json:"transferType"`     // 转帐类型 1微信企业付款到零钱 2微信企业付款到银行卡
			State                   int    `json:"state"`            // 转帐状态 2(已处理)
			VerifyStatus            int    `json:"verifyStatus"`     // 验证帐态 2(审核通过)
			OperateNote             string `json:"operateNote"`      // 操作说明 系统自动转账成功
			OperateDate             string `json:"operateDate"`      // 操作时间
			UpdateDate              string `json:"updateDate"`       // 更新时间
			CreateDate              string `json:"createDate"`       // 新增时间
			ReceivingAccount        string `json:"receivingAccount"` // 收款帐户  微信公众号openid o07U5wueUxDhwUN1wGjK35_22Huc
			ReceivingType           int    `json:"receivingType"`    // 收款类型 1 微信转帐
			// 转帐信息  -- 转帐订单表
			TransferOrder struct {
				TradeNo       string `json:"tradeNo"`       // 订单编号 1608786614252
				UserID        int    `json:"userId"`        // 用户ID 100139
				BusinessType  int    `json:"businessType"`  // 业务类型
				TransferType  int    `json:"transferType"`  // 1微信企业付款到零钱 2微信企业付款到银行卡
				Money         int    `json:"money"`         // 转帐金额 单位 分
				Note          string `json:"note"`          // 转帐说明 代理商提现
				State         int    `json:"state"`         // 状态 2 已完成
				UpdateDate    string `json:"updateDate"`    // 更新时间
				CreateDate    string `json:"createDate"`    // 创建时间
				ReceivingInfo string `json:"receivingInfo"` // 收款信息 json appid,openid
				ReceivingType int    `json:"receivingType"` // 收款类型 1 微信转帐
				WxAppID       string `json:"wxAppId"`       // 公众号Appid  wxac3043809b020884
				WxOpenID      string `json:"wxOpenId"`      // 微信公众号openid o07U5wueUxDhwUN1wGjK35_22Huc
				PayeeID       string `json:"payeeId"`       // 收款人ID  openid o07U5wueUxDhwUN1wGjK35_22Huc
				PayeeType     int    `json:"payeeType"`     // 收款类型 1 微信转帐
			} `json:"transferOrder"`
			MoneyStr          string `json:"moneyStr"`          // 金额字符串 50元
			StateName         string `json:"stateName"`         // 状态 2 已处理
			ReceivingTypeName string `json:"receivingTypeName"` // 收款类型 微信转帐
			TransferMoneyStr  string `json:"transferMoneyStr"`  // 转帐金额 字符串 50元
			VerifyStatusName  string `json:"verifyStatusName"`  // 2 审核通过
			User              struct {
				ID          int    `json:"id"`          // 用户ID 100139
				OpenID      string `json:"openId"`      // openid
				Nickname    string `json:"nickname"`    // 用户昵称 金城宾馆
				Name        string `json:"name"`        // 用户姓名 郭 -- 申请人
				Language    string `json:"language"`    // 语言
				Sex         int    `json:"sex"`         // 性别 0
				FaceImg     string `json:"faceImg"`     // 头像
				Phone       string `json:"phone"`       // 手机号码
				PhoneCode   string `json:"phoneCode"`   // 手机国家   代码
				Country     string `json:"country"`     // 国家
				Province    string `json:"province"`    // 省份
				City        string `json:"city"`        // 城市
				Status      int    `json:"status"`      // 状态 1 可用
				CreateDate  string `json:"createDate"`  // 注册时间
				Age         int    `json:"age"`         // 年龄
				StatusName  string `json:"statusName"`  // 状态名 可用
				SexName     string `json:"sexName"`     // 性别 女
				PhoneNumber string `json:"phoneNumber"` // 电话号码
			} `json:"user,omitempty"`
		} `json:"data"`
	} `json:"body"`
}

// ----------------------------更新会员----------------------------//

func (logic *SyncLogic) UpdateMemberLogic(page, pageSize int, cookie string) ([]string, error) {
	path := fmt.Sprintf("./data/members/%s", time.Now().Format("20060102150405"))
	url := "http://mng.yundian.ink/mng/10041/user/member/list.data"

	// 抓取
	err := logic.doRequestMembers(page, pageSize, url, path, cookie)
	if err != nil {
		return nil, err
	}

	var strs []string
	for i := 1; i <= page; i++ {
		strMember := logic.taskMembers(i, path)
		strs = append(strs, strMember)
	}

	return strs, nil
}

func (logic *SyncLogic) doRequestMembers(pages, pageSize int, url, path, cookie string) error {
	client := resty.New()
	for i := 1; i <= pages; i++ {
		m := map[string]string{}
		m["page"] = strconv.Itoa(i)
		m["limit"] = strconv.Itoa(pageSize)
		resp, err := client.R().
			SetHeader("Content-Type", "application/x-www-form-urlencoded").
			SetFormData(m).
			SetHeader("Cookie", cookie).
			Post(url)
		if err != nil {
			return err
		}
		msg := new(msgResp)
		_ = json.Unmarshal(resp.Body(), &msg)
		if msg.Code != 200 && msg.Msg != "" {
			return errors.New(msg.Msg)
		}
		// 创建
		err = helper.MakeDir(path)
		if err != nil {
			return err
		}
		err = ioutil.WriteFile(path+fmt.Sprintf("/%d.json", i), resp.Body(), 666)
		if err != nil {
			return err
		}
	}
	return nil
}

func (logic *SyncLogic) taskMembers(i int, path string) string {
	lists := new(membersGenerated)
	viper.SetConfigFile(path + fmt.Sprintf("/%d.json", i))
	if err := viper.ReadInConfig(); err != nil {
		log.Fatal("viper.ReadInConfig failed : ", err.Error())
	}
	// 反序列化到struct
	if err := viper.Unmarshal(lists); err != nil {
		log.Fatal("viper.Unmarshal failed : ", err.Error())
	}

	// 写入数据库
	var ucount, ccount int
	for _, lst := range lists.Body.Data {
		m := membermodel.New()
		m.UUID = lst.ID // id
		m.RegFrom = "wx_xcx"
		m.NickName = lst.Nickname
		m.Headimgurl = lst.FaceImg
		m.XcxOpenid = lst.WxxcxOpenID

		m.CreateAt = dingo.Time(wechatpay.StrTimeToInt(lst.CreateDate))
		m.UpdateAt = dingo.Time(wechatpay.StrTimeToInt(lst.UpdateDate))

		// 查询 库中是否存在此数据
		var count int64
		global.Orm.Table("members").Where("uuid = ?", lst.ID).Count(&count)
		if count > 0 {
			ucount++
			global.Orm.Table("members").Where("uuid = ?", lst.ID).Model(&m).Updates(m)
		} else { // 新增
			ccount++
			global.Orm.Table("members").Create(m)
		}
	}
	str := fmt.Sprintf("当前页-%d,新增%d条,更新%d条 \n", i, ccount, ucount)
	return str
}

type membersGenerated struct {
	Body struct {
		Total int `json:"total"`
		Data  []struct {
			ID          string `json:"id"`
			LoginToken  string `json:"loginToken"`
			Type        int    `json:"type"`
			Nickname    string `json:"nickname"`
			FaceImg     string `json:"faceImg"`
			WxxcxOpenID string `json:"wxxcxOpenId"`
			UpdateDate  string `json:"updateDate"`
			CreateDate  string `json:"createDate"`
			TypeName    string `json:"typeName"`
		} `json:"data"`
	} `json:"body"`
}

// ----------------------------更新商户价格(免押密码线充)----------------------------//

func (logic *SyncLogic) UpdatePricesLogic(deviceTypeId int, cookie string) ([]string, error) {
	path := fmt.Sprintf("./data/prices/%d/%s", deviceTypeId, time.Now().Format("20060102150405"))

	var lists []placeresp.GetPlaceIdWithHotelId
	global.Orm.Table("places").Find(&lists)
	for _, lst := range lists {
		url := fmt.Sprintf("http://mng.yundian.ink/mng/10041/dynamic/pcl/2/place/virtualProduct.html?deviceTypeId=%d&placeId=%d", deviceTypeId, lst.Id)
		err := logic.DoRequestPrices(lst.Id, url, path, cookie) // 抓取订单信息
		if err != nil {
			return nil, err
		}
	}

	var strs []string
	//for _,lst := range lists {
	//	om := orders.New()
	//	sql := `SELECT product_id,place_id FROM orders WHERE place_id=? ORDER BY create_at limit 1`
	//	global.Orm.Raw(sql, lst.Id).Find(&om)
	//	b,_ := ioutil.ReadFile(path + fmt.Sprintf("/%d.html", lst.Id))
	//	m := logic.getAttr(string(b), om.ProductId, lst.Id)
	//
	//	var count int64
	//	global.Orm.Table("prices").Where("place_id = ? and device_type_id = ?", lst.Id, deviceTypeId).Count(&count)
	//	if count > 0 {
	//		// 判断product_id是否相同
	//		op := prices.New()
	//		sql := `SELECT product_id,place_id FROM prices WHERE place_id= ?  and device_type_id = ? ORDER BY create_at limit 1`
	//		global.Orm.Raw(sql, lst.Id, deviceTypeId).Find(&op)
	//
	//		if om.ProductId != op.ProductId {
	//			if om.ProductId != "" {
	//				strs = append(strs, fmt.Sprintf("商户%s价格有变更", lst.PlaceName))
	//				// 订单om.productId 与 价格表中的 productId 不相同
	//				// 新增
	//				m.ProductId = om.ProductId
	//				global.Orm.Table("prices").Create(m)
	//				strs = append(strs, fmt.Sprintf("商户%s价格变更后，新价格新增成功", lst.PlaceName))
	//			}
	//		} else {
	//			global.Orm.Table("prices").Where("place_id = ? and device_type_id = ?", lst.Id, deviceTypeId).Model(&m).Updates(m)
	//			strs = append(strs, fmt.Sprintf("商户%s价格更新成功", lst.PlaceName))
	//		}
	//	} else { // 新增
	//		global.Orm.Table("prices").Create(m)
	//		strs = append(strs, fmt.Sprintf("商户%s价格新增成功", lst.PlaceName))
	//	}
	//}
	//
	return strs, nil
}

func (logic *SyncLogic) DoRequestPrices(placeId int, url, path, cookie string) error {
	client := resty.New()
	resp, err := client.R().
		SetHeader("Cookie", cookie).
		Get(url)
	if err != nil {
		return err
	}
	msg := new(msgResp)
	_ = json.Unmarshal(resp.Body(), &msg)
	if msg.Code != 200 && msg.Msg != "" {
		return errors.New(msg.Msg)
	}
	// 创建
	err = helper.MakeDir(path)
	if err != nil {
		return err
	}
	err = ioutil.WriteFile(path+fmt.Sprintf("/%d.html", placeId), resp.Body(), 666)
	if err != nil {
		return err
	}
	return nil
}

func (logic *SyncLogic) GetAttr(b string, productId string, pId int) *prices.PriceModel {
	if productId == "" {
		t := time.Now().String()
		str := utils.Join(t, strconv.Itoa(pId))
		productId = utils.Str2Md5(str)
	}
	// Load the HTML document
	doc, err := goquery.NewDocumentFromReader(strings.NewReader(b))
	if err != nil {
		log.Fatal(err)
	}

	// 网点ID
	var placeId int
	if val, ok := doc.Find("input[name='placeId']").Attr("value"); ok {
		placeId, _ = strconv.Atoi(val)
	}
	//if pId != placeId {
	//	log.Println("---------------网点ID不相同---------------")
	//	return nil
	//}

	// 类型ID
	var deviceTypeId int
	if val, ok := doc.Find("input[name='deviceTypeId']").Attr("value"); ok {
		deviceTypeId, _ = strconv.Atoi(val)
	}

	// depositPrice 押金
	var depositPrice int
	if val, ok := doc.Find("input[name='depositPrice']").Attr("value"); ok {
		depositPrice, _ = strconv.Atoi(val)
	}
	// baseTimes 最少使用
	var baseTimes int
	if val, ok := doc.Find("input[name='baseTimes']").Attr("value"); ok {
		baseTimes, _ = strconv.Atoi(val)
	}

	// 最低使用费用
	var basePrice int
	if val, ok := doc.Find("input[name='basePrice']").Attr("value"); ok {
		basePrice, _ = strconv.Atoi(val)
	}

	// payInterval 每使用
	var payInterval int
	if val, ok := doc.Find("input[name='payInterval']").Attr("value"); ok {
		payInterval, _ = strconv.Atoi(val)
	}

	// 费用
	var payIntervalPrice int
	if val, ok := doc.Find("input[name='payIntervalPrice']").Attr("value"); ok {
		payIntervalPrice, _ = strconv.Atoi(val)
	}

	// 免费时长
	var freeTimes int
	if val, ok := doc.Find("input[name='freeTimes']").Attr("value"); ok {
		freeTimes, _ = strconv.Atoi(val)
	}

	// 日最大消费
	var maxPayPrice int
	if val, ok := doc.Find("input[name='maxPayPrice']").Attr("value"); ok {
		maxPayPrice, _ = strconv.Atoi(val)
	}

	// 最大使用时长
	var maxTimes int
	if val, ok := doc.Find("input[name='maxTimes']").Attr("value"); ok {
		maxTimes, _ = strconv.Atoi(val)
	}

	if depositPrice == 0 && baseTimes == 0 &&
		basePrice == 0 && payInterval == 0 &&
		payIntervalPrice == 0 && freeTimes == 0 && maxPayPrice == 0 {
		return nil
	} else {
		return &prices.PriceModel{
			DeviceTypeId:     deviceTypeId,
			PlaceId:          placeId,
			Deposit:          int64(depositPrice),
			BaseTimes:        baseTimes,
			BasePrice:        int64(basePrice),
			PayInterval:      payInterval,
			PayIntervalPrice: int64(payIntervalPrice),
			FreeTimes:        freeTimes,
			MaxTime:          maxTimes,
			MaxPayPrice:      int64(maxPayPrice),
			ProductId:        productId,
			CreateAt:         dingo.Time(time.Now().Unix()),
		}
	}

}

// ----------------------------更新用户信息----------------------------//

func (logic *SyncLogic) UpdateUserInfoCountLogic(cookie string) ([]string, error) {
	path := fmt.Sprintf("./data/users/info/%s", time.Now().Format("20060102150405"))

	var lists []users.UserModel
	global.Orm.Table("users").Find(&lists)
	for _, lst := range lists {
		url := fmt.Sprintf("http://mng.yundian.ink/mng/10041/user/agent/info.html?id=%d", lst.ID)
		err := logic.doRequestUserInfo(lst.ID, url, path, cookie) // 抓取订单信息
		if err != nil {
			return nil, err
		}
	}

	var strs []string

	return strs, nil
}

func (logic *SyncLogic) doRequestUserInfo(placeId int, url, path, cookie string) error {
	client := resty.New()
	resp, err := client.R().
		SetHeader("Cookie", cookie).
		Get(url)
	if err != nil {
		return err
	}
	msg := new(msgResp)
	_ = json.Unmarshal(resp.Body(), &msg)
	if msg.Code != 200 && msg.Msg != "" {
		return errors.New(msg.Msg)
	}
	// 创建
	err = helper.MakeDir(path)
	if err != nil {
		return err
	}
	err = ioutil.WriteFile(path+fmt.Sprintf("/%d.html", placeId), resp.Body(), 666)
	if err != nil {
		return err
	}
	return nil
}

// ----------------------------计费规则------------------------------//
//func (logic *SyncLogic) DotaskPlaceRules(targetPath string) {
//f, err := excelize.OpenFile(targetPath)
//if err != nil {
//	println(err.Error())
//	return
//}
//// 获取工作表中指定单元格的值
////cell := f.GetCellValue("Sheet1", "B2")
////if err != nil {
////	println(err.Error())
////	return
////}
////println(cell)
//// 获取 Sheet1 上所有单元格
//rows := f.GetRows("网点ID")
//for _, row := range rows {
//	for _, colCell := range row {
//		print(colCell, "\t")
//	}
//	println()
//}
//}

func (logic *SyncLogic) DotaskPlaceRules(isType, addNum int, path string) string {
	type PlaceRules struct {
		FreeTimes        interface{} `json:"free_times"`
		Deposit          interface{} `json:"deposit"`
		MaxPayPrice      interface{} `json:"max_pay_price"`
		BasePrice        interface{} `json:"base_price"`
		MaxTime          interface{} `json:"max_time"`
		PayInterval      interface{} `json:"pay_interval"`
		PlaceId          interface{} `json:"place_id"`
		PayIntervalPrice interface{} `json:"pay_interval_price"`
	}

	var lists []PlaceRules
	data, err := ioutil.ReadFile(path)
	err = json.Unmarshal(data, &lists)
	if err != nil {
		fmt.Println(err.Error())
		return ""
	}

	// 写入数据库
	ucount := 0
	ccount := 0
	for _, lst := range lists {
		m := &prices.PriceModel{}
		//   let free_times,deposit,max_pay_price,base_price,max_time,pay_interval,place_id,pay_interval_price

		if typeof(lst.PlaceId) != "float64" || typeof(lst.MaxTime) != "float64" {
			continue
		}

		m.PlaceId = int(lst.PlaceId.(float64)) + addNum
		m.DeviceTypeId = isType
		m.ProductId = utils.Str2Md5(helper.GenerateUUID())
		m.Status = 1
		m.Priority = 10
		if isType == 10 {
			if lst.Deposit != nil {
				m.Deposit = int64(lst.Deposit.(float64)) * 100
			}
			if lst.MaxPayPrice != nil {
				m.MaxPayPrice = int64(lst.MaxPayPrice.(float64)) * 100
			}
			if lst.BasePrice != nil {
				m.BasePrice = int64(lst.BasePrice.(float64)) * 100
			}
			if lst.MaxTime != nil {
				m.MaxTime = int(lst.MaxTime.(float64)) / 60
			}
			if lst.PayInterval != nil {
				m.PayInterval = int(lst.PayInterval.(float64)) / 60
			}
			if lst.PayInterval != nil {
				m.PayIntervalPrice = int64(lst.PayIntervalPrice.(float64)) * 100
			}

			if result := global.Orm.Table("prices").Create(m); result.Error != nil {
				logs.Error(result.Error)
			}
		}

		if isType == 12 {
			if typeof(lst.PayIntervalPrice) != "float64" || (int(lst.MaxTime.(float64)/60) > 0 && int64(lst.PayIntervalPrice.(float64)) > 0) {
				continue
			}

			numList := strings.Split(fmt.Sprintf("%v", lst.MaxTime.(float64)/60), ".")
			if len(numList) > 1 && (numList[1] != "0" && numList[1] != "") {
				logs.Info(lst)
				m.RuleName = fmt.Sprintf("%v元,使用%v分钟", lst.PayIntervalPrice, lst.MaxTime)
			} else {
				m.RuleName = fmt.Sprintf("%v元,使用%v小时", lst.PayIntervalPrice, lst.MaxTime.(float64)/60)
			}
			m.UseDuration = int(lst.MaxTime.(float64))
			m.PayMoney = int64(lst.PayIntervalPrice.(float64) * 100)
			m.CreateAt = dingo.Time(time.Now().Unix())

			var count int64
			if db := global.Orm.Debug().Table("prices").
				Where("place_id=? AND use_duration=? AND pay_money=? AND device_type_id=?", m.PlaceId, m.UseDuration, m.PayMoney, m.DeviceTypeId).
				Count(&count); db.Error != nil {
				logs.Error(db.Error)
			}
			if count == 0 && lst.MaxTime.(float64) > 0 {
				if result := global.Orm.Table("prices").Create(m); result.Error != nil {
					logs.Error(result.Error)
				}
			}
		}

		//global.Orm.Table("users").Where("id = ?", m.ID).Count(&count)
		//if count > 0 {
		//	ucount++
		//	global.Orm.Table("users").Where("id = ?", m.ID).Model(&m).Updates(m)
		//} else { // 新增
		//	ccount++
		//	global.Orm.Table("users").Create(m)
		//}
	}
	//fmt.Printf("当前页面%d, 更新成功%d条，新增成功%d条 \n", i, ucount, ccount)
	str := fmt.Sprintf("当前页面%d, 更新成功%d条，新增成功%d条 \n", ucount, ccount)
	//return str

	//str := fmt.Sprintf("更新成功%d条，新增成功%d条 \n", 0, 0)
	return str
}

func (logic *SyncLogic) DotaskRemoveUser() {
	userPhoneList := make([]*users.UserModel, 0)
	removeUsersMap := map[int]int{}
	removeTargetUsers := []int{}
	removeUsers := []int{}
	removePlace := []int{}

	sql := `SELECT * FROM users WHERE phone IN (
    SELECT a.phone FROM (SELECT count(phone) num, phone,name,user_name FROM users GROUP BY phone) a WHERE num>1 ORDER BY num DESC)
	`
	if db := global.Orm.Debug().Raw(sql).Find(&userPhoneList); db.Error != nil {
		logs.Error(db.Error)
	}

	for _, item := range userPhoneList {
		userIdArr := dao.NewUserDao().QueryChildUserIds(item.ID).Unwrap().([]int)
		userIdArr = append(userIdArr, item.ID)
		placeModelLst := dao.NewPlaceDao().GetPlaceByParentIds(userIdArr).Unwrap().([]*placemodel.PlaceModel)
		placeIdArr := make([]int, 0)
		for _, placeModel := range placeModelLst {
			placeIdArr = append(placeIdArr, placeModel.Id)
		}
		var count int64
		if len(placeIdArr) > 0 && len(placeIdArr) < 1000 {
			if db := global.Orm.Debug().Table("devices d").Where("d.place_id in ?", placeIdArr).Count(&count); db.Error != nil {
				logs.Error(db.Error)
			}
		}

		//if count == 0 && !(removeUsersMap[item.ID] > 0)  && len(placeIdArr) < 1000 {
		//	removeUsersMap[item.ID] = item.ID
		//	removeUsers = append(removeUsers, item.ID)
		//	removeUsers = append(removeUsers, userIdArr...)
		//	removePlace = append(removePlace, removePlace...)
		//	//if db := global.Orm.Debug().Exec("DELETE FROM users WHERE id>300000 AND id IN ?", removeUsers); db.Error != nil {
		//	//	logs.Error(db.Error)
		//	//}
		//	//if db := global.Orm.Debug().Exec("DELETE FROM places WHERE user_id>300000 AND id IN ?", removePlace); db.Error != nil {
		//	//	logs.Error(db.Error)
		//	//}
		//}
		if count > 0 {
			removeUsersMap[item.ID] = item.ID
			removeUsers = append(removeUsers, item.ID)
			removeUsers = append(removeUsers, userIdArr...)
			removePlace = append(removePlace, placeIdArr...)
			//if db := global.Orm.Debug().Exec("DELETE FROM users WHERE id>300000 AND id IN ?", removeUsers); db.Error != nil {
			//	logs.Error(db.Error)
			//}
			//if db := global.Orm.Debug().Exec("DELETE FROM places WHERE user_id>300000 AND id IN ?", removePlace); db.Error != nil {
			//	logs.Error(db.Error)
			//}
		}
	}
	for _, id := range removeUsersMap {
		removeTargetUsers = append(removeTargetUsers, id)
	}
	log.Println(removeTargetUsers)
	log.Println(removeUsers)
	log.Println(removePlace)
}

func (logic *SyncLogic) DotaskRemoveUserUpdate(isType int) {
	userPhoneList := make([]*users.UserModel, 0)

	var userUpdateListIds []int
	var placesUpdateListIds []int
	var placesBranchUpdateListIds []int
	var orderUpdateListIds []int
	var orderAgentUpdateListIds []int
	var dividendsUpdateListIds []int
	var cashUpdateListIds []int
	var agentIncomehUpdateListIds []int
	var branchIncomehUpdateListIds []int
	var removeUserIds []int

	//sql := `SELECT * FROM users WHERE id IN (
	//132,524,300055,400011,400109,400607,401075,401444,401717,401737,401741,547,300077,301028,301050,301086,400025,401519,301103,301104,400002,400546,401762,300068,300075,301106,400097,401474,735,851,300039,301032,400354,400562,401473,301073,301085,301101,301123,400771,217,849,300086,301071,400530,219,301069,400003,401094,
	//300755,300800,300932,576,300907,300692,300012,300992,525,300659,300816,527,301038,221,947,300714,523,300568,300660,300251,
	//300001,401281,300696,400601,300845,300093,300170,400602,300661
	//) AND is_place<>3
	//`
	//sql := `SELECT * FROM users WHERE id IN (300941,400898,400431,400593,401747,301049,300468,400293,400660)`
	sql := `SELECT * FROM users WHERE id IN (301042,400599)`

	if db := global.Orm.Debug().Raw(sql).Find(&userPhoneList); db.Error != nil {
		logs.Error(db.Error)
	}

	for _, item := range userPhoneList {
		targetUser := users.UserModel{}
		if db := global.Orm.Debug().Table("users").Where("phone=? AND id<>?", item.Phone, item.ID).First(&targetUser); db.Error != nil {
			logs.Error(db.Error)
		}
		if targetUser.ID == 0 {
			continue
		}

		userUpdateList := make([]*users.UserModel, 0)
		if db := global.Orm.Debug().Table("users u").Where("u.parent_id=? AND is_place<>?", item.ID, 3).Find(&userUpdateList); db.Error != nil {
			logs.Error(db.Error)
		}

		placesUpdateList := make([]*placemodel.PlaceModel, 0)
		if db := global.Orm.Debug().Table("places p").Where("p.user_id=?", item.ID).Find(&placesUpdateList); db.Error != nil {
			logs.Error(db.Error)
		}

		placesBranchUpdateList := make([]*placemodel.PlaceModel, 0)
		if db := global.Orm.Debug().Table("places p").Where("p.branch_user_id=?", item.ID).Find(&placesBranchUpdateList); db.Error != nil {
			logs.Error(db.Error)
		}

		orderUpdateList := make([]*orders.OrderDetail, 0)
		if db := global.Orm.Debug().Table("orders o").Where("o.user_id=?", item.ID).Find(&orderUpdateList); db.Error != nil {
			logs.Error(db.Error)
		}
		orderAgentUpdateList := make([]*orders.OrderDetail, 0)
		if db := global.Orm.Debug().Table("orders o").Where("o.agent_user_id=?", item.ID).Find(&orderAgentUpdateList); db.Error != nil {
			logs.Error(db.Error)
		}

		dividendsUpdateList := make([]*dividendslog.DividendsLog, 0)
		if db := global.Orm.Debug().Table("dividends_log dl").Where("dl.user_id=?", item.ID).Find(&dividendsUpdateList); db.Error != nil {
			logs.Error(db.Error)
		}

		cashUpdateList := make([]*cashlog.CashLogModel, 0)
		if db := global.Orm.Debug().Table("cash_log cl").Where("cl.user_id=?", item.ID).Find(&cashUpdateList); db.Error != nil {
			logs.Error(db.Error)
		}

		agentIncomehUpdateList := make([]*agentincome.AgentIncomeModel, 0)
		if db := global.Orm.Debug().Table("agent_income ai").Where("ai.agent_user_id=?", item.ID).Find(&agentIncomehUpdateList); db.Error != nil {
			logs.Error(db.Error)
		}

		branchIncomehUpdateList := make([]*agentincome.BranchIncomeModel, 0)
		if db := global.Orm.Debug().Table("branch_income bi").Where("bi.agent_user_id=?", item.ID).Find(&branchIncomehUpdateList); db.Error != nil {
			logs.Error(db.Error)
		}

		if isType == 1 {
			if db := global.Orm.Debug().Table("users").Where("parent_id=?", item.ID).Update("parent_id", targetUser.ID); db.Error != nil {
				logs.Error(db.Error)
			}
			if db := global.Orm.Debug().Table("places").Where("user_id=?", item.ID).Update("user_id", targetUser.ID); db.Error != nil {
				logs.Error(db.Error)
			}
			if db := global.Orm.Debug().Table("places").Where("branch_user_id=?", item.ID).Update("branch_user_id", targetUser.ID); db.Error != nil {
				logs.Error(db.Error)
			}
			if db := global.Orm.Debug().Table("orders o").Where("o.user_id=?", item.ID).Update("o.user_id", targetUser.ID); db.Error != nil {
				logs.Error(db.Error)
			}
			if db := global.Orm.Debug().Table("orders o").Where("o.agent_user_id=?", item.ID).Update("o.agent_user_id", targetUser.ID); db.Error != nil {
				logs.Error(db.Error)
			}
			if db := global.Orm.Debug().Table("dividends_log dl").Where("dl.user_id=?", item.ID).Update("dl.user_id", targetUser.ID); db.Error != nil {
				logs.Error(db.Error)
			}
			if db := global.Orm.Debug().Table("cash_log cl").Where("cl.user_id=?", item.ID).Update("cl.user_id", targetUser.ID); db.Error != nil {
				logs.Error(db.Error)
			}
			if db := global.Orm.Debug().Table("agent_income ai").Where("ai.agent_user_id=?", item.ID).Update("ai.agent_user_id", targetUser.ID); db.Error != nil {
				logs.Error(db.Error)
			}
			if db := global.Orm.Debug().Table("branch_income bi").Where("bi.agent_user_id=?", item.ID).Update("bi.agent_user_id", targetUser.ID); db.Error != nil {
				logs.Error(db.Error)
			}
		}

		for _, item := range userUpdateList {
			userUpdateListIds = append(userUpdateListIds, item.ID)
		}
		for _, item := range placesUpdateList {
			placesUpdateListIds = append(placesUpdateListIds, item.Id)
		}
		for _, item := range placesBranchUpdateList {
			placesBranchUpdateListIds = append(placesBranchUpdateListIds, item.Id)
		}
		for _, item := range orderUpdateList {
			orderUpdateListIds = append(orderUpdateListIds, item.Id)
		}
		for _, item := range orderAgentUpdateList {
			orderAgentUpdateListIds = append(orderAgentUpdateListIds, item.Id)
		}
		for _, item := range dividendsUpdateList {
			dividendsUpdateListIds = append(dividendsUpdateListIds, item.Id)
		}
		for _, item := range cashUpdateList {
			cashUpdateListIds = append(cashUpdateListIds, item.ID)
		}
		for _, item := range agentIncomehUpdateList {
			agentIncomehUpdateListIds = append(agentIncomehUpdateListIds, item.Id)
		}
		for _, item := range branchIncomehUpdateList {
			branchIncomehUpdateListIds = append(branchIncomehUpdateListIds, item.Id)
		}

		removeUserIds = append(removeUserIds, item.ID)
	}

	tmp := []map[string]interface{}{}
	log.Println("userUpdateListIds===================")
	global.Orm.Debug().Table("users").Where("id in ?", userUpdateListIds).Find(&tmp)
	//log.Println(userUpdateListIds)

	log.Println("placesUpdateListIds===================")
	tmp = []map[string]interface{}{}
	global.Orm.Debug().Table("places").Where("id in ?", placesUpdateListIds).Find(&tmp)
	//log.Println(placesUpdateListIds)

	log.Println("placesBranchUpdateListIds===================")
	tmp = []map[string]interface{}{}
	global.Orm.Debug().Table("places").Where("id in ?", placesBranchUpdateListIds).Find(&tmp)

	log.Println("orderUpdateListIds===================")
	tmp = []map[string]interface{}{}
	global.Orm.Debug().Table("orders").Where("id in ?", orderUpdateListIds).Find(&tmp)
	//log.Println(orderUpdateListIds)

	log.Println("orderAgentUpdateListIds===================")
	tmp = []map[string]interface{}{}
	global.Orm.Debug().Table("orders").Where("id in ?", orderAgentUpdateListIds).Find(&tmp)
	//log.Println(orderAgentUpdateListIds)

	log.Println("dividendsUpdateListIds===================")
	tmp = []map[string]interface{}{}
	global.Orm.Debug().Table("dividends_log dl").Where("id in ?", dividendsUpdateListIds).Find(&tmp)
	//log.Println(dividendsUpdateListIds)

	log.Println("cashUpdateListIds===================")
	tmp = []map[string]interface{}{}
	global.Orm.Debug().Table("cash_log cl").Where("cl.id in ?", cashUpdateListIds).Find(&tmp)
	//log.Println(cashUpdateListIds)

	log.Println("agentIncomehUpdateListIds===================")
	tmp = []map[string]interface{}{}
	global.Orm.Debug().Table("agent_income ai").Where("ai.id in ?", agentIncomehUpdateListIds).Find(&tmp)
	//log.Println(agentIncomehUpdateListIds)

	log.Println("branchIncomehUpdateListIds===================")
	tmp = []map[string]interface{}{}
	global.Orm.Debug().Table("branch_income bi").Where("bi.id in ?", branchIncomehUpdateListIds).Find(&tmp)
	//log.Println(branchIncomehUpdateListIds)

	log.Println("removeUserIds===================")
	tmp = []map[string]interface{}{}
	global.Orm.Debug().Table("users").Where("id in ?", removeUserIds).Find(&tmp)
	//log.Println(removeUserIds)
}

func typeof(v interface{}) string {
	switch t := v.(type) {
	case int:
		return "int"
	case float64:
		return "float64"
	default:
		_ = t
		return "unknown"
	}
}
